我不确定我是否可以在一个查询中执行此操作,但我想。
我需要这样的所有记录:
SELECT a.field_1, a.field_2, b.field_3, b.field_4
FROM tbl_a AS a, tbl_b AS b
WHERE a.field_1 = b.field_3
我还想排除属于这种情况的记录:
IF a.field_1 IN (1,2,3,4)
AND a.field_date < NOW()
更新:(抱歉混淆)
将这两项结果合并到一个查询中的任何想法
备注(如果这有所不同):
答案 0 :(得分:2)
这样的东西?
SELECT a.field_1, a.field_2, b.field_3, b.field_4
FROM tbl_a AS a, tbl_b AS b
WHERE a.field_1 = b.field_3
AND (
CASE WHEN a.field_1 IN (1,2,3,4) THEN
CASE WHEN A.FIELD_DATE = NOW() THEN 1 ELSE 0
END
ELSE 1
END) = 1
答案 1 :(得分:0)
这是一个应该有效的代码:
SELECT a.field_1, a.field_2, b.field_3, b.field_4
FROM tbl_a AS a
INNER JOIN tbl_b AS b ON a.field_1 = b.field_3
WHERE
(a.field_1 IN (1,2,3,4) AND a.field_date = NOW())
OR
(a.field_1 NOT IN (1,2,3,4))
请注意,如果a.field是unsigned int!= 0,您可以替换:
a.field_1 IN (1,2,3,4)
a.field_1 <=4
a.field_1 NOT IN (1,2,3,4)
和a.field_1 > 4
与{{1}}
如果大型记录集存在问题,这将使其更快
答案 2 :(得分:0)
让我们用正确的JOIN重写它,并在条件上添加NOT以排除:
SELECT a.field_1, a.field_2, b.field_3, b.field_4
FROM tbl_a AS a JOIN tbl_b AS b ON (a.field_1 = b.field_3)
WHERE NOT (a.field_1 IN (1,2,3,4) AND a.field_date < NOW())
由于NOT(X和Y)等同于(NOT X)OR(NOT Y),您可以将其重写为:
SELECT a.field_1, a.field_2, b.field_3, b.field_4
FROM tbl_a AS a JOIN tbl_b AS b ON (a.field_1 = b.field_3)
WHERE a.field_1 NOT IN (1,2,3,4) OR a.field_date >= NOW())
但是我们还需要知道field_1或field_date是否可以为NULL。如果是这种情况,如果foo为NULL,则表达式“foo NOT IN(blah)”将返回NULL。所以你需要对此更加具体。