三个表,列如下:
A: A_id, B_id, C_id, flag, ...
B: B_id, date, ...
C: C_id, date
如果A.flag为NULL,那么我需要来自A的所有行与B_id上的B一起加入过去的B.date。
如果A.flag不是NULL,那么我需要A中的所有行与B_id上的B连接,过去有C.date,C在C_id上连接。
尝试:
SELECT *
FROM A, B, C
WHERE A.A_id = B.B_id
AND ((A.flag IS NULL AND (NOW() > B.date) OR
(A.flag IS NOT NULL AND (NOW() > C.date) AND C.C_id = A.C_id))
但是我需要A.flag is NULL
行中的某些条件来阻止它加入来自C的每一行。这是我无法解决的问题。
或者有更简单的方法吗?
答案 0 :(得分:3)
你可以尝试
SELECT a.*, b.*
FROM a INNER JOIN b ON a.B_id = b.B_id
WHERE a.flag IS NULL AND b.date < NOW()
UNION
SELECT a.*, b.*
FROM a INNER JOIN b ON a.B_id = b.B_id
INNER JOIN c ON a.C_id = c.C_id
WHERE a.flag IS NOT NULL AND c.date < NOW()
答案 1 :(得分:0)
这可能会为你做到这一点!
SELECT a.*
FROM A AS a
LEFT JOIN B AS b ON b.b_id = a.b_id AND NOW() > b.date AND a.flag IS NULL
LEFT JOIN C AS c ON c.c_id = a.c_id AND NOW() > c.date AND a.flag IS NOT NULL
如果您只希望A中符合这些条件的行,则需要添加如下所示的位置:
WHERE b.b_id IS NOT NULL OR c.c_id IS NOT NULL
否则你最终会得到A中的所有行。:)
完整的查询将是:
SELECT a.*
FROM A AS a
LEFT JOIN B AS b ON b.b_id = a.b_id AND NOW() > b.date AND a.flag IS NULL
LEFT JOIN C AS c ON c.c_id = a.c_id AND NOW() > c.date AND a.flag IS NOT NULL
WHERE b.b_id IS NOT NULL OR c.c_id IS NOT NULL
答案 2 :(得分:0)
这样的事情也可能有效:
SELECT *
FROM A
WHERE A.flag IS NULL
AND EXISTS (SELECT * FROM B WHERE date < NOW() AND B_id = A.A_id)
OR A.flag IS NOT NULL
AND EXISTS (SELECT * FROM C WHERE date < NOW() AND C_id = A.A_id)