我有一张表my_table
看起来像 -
+---------------------+---------------------+
| phone | status |
+---------------------+---------------------+
| 019 | NI |
+---------------------+---------------------+
| 019 | DROP |
+---------------------+---------------------+
| 019 | SALE |
+---------------------+---------------------+
| 018 | B |
+---------------------+---------------------+
| 016 | DROP |
+---------------------+---------------------+
我的查询
SELECT DISTINCT(phone) AS phone FROM my_table WHERE status NOT IN ('NI','SALE','B')
RESULT
+---------------------+
| phone |
+---------------------+
| 019 |
+---------------------+
| 016 |
+---------------------+
但我想在下面
+---------------------+
| phone |
+---------------------+
| 016 |
+---------------------+
我的查询结果中不需要手机019
。因为电话019
已经有NI
和SALE
状态。
如何通过更新我的查询来实现?
答案 0 :(得分:4)
我使用反连接模式:
SELECT t.phone
FROM my_table t
LEFT
JOIN my_table r
ON r.phone = t.phone
AND r.status IN ('NI','SALE','B')
WHERE r.phone IS NULL
GROUP BY t.phone
这样想。我们可以获得所有phone
值的列表...
我们可以获得状态为“NI”,“SALE”或“B”的phone
值列表。
诀窍是从“全部”列表中返回phone
的值,不包括第二个列表中的值。
反连接只是一种选择;还有其他查询模式将返回相同的结果。
其他一些选项是NOT EXISTS子查询...
SELECT t.phone
FROM my_table t
WHERE NOT EXISTS ( SELECT 1
FROM my_table r
WHERE r.phone = t.phone
AND r.status IN ('NI','SALE','B')
)
GROUP BY t.phone
另一种选择是条件聚合......
SELECT t.phone
FROM my_table t
GROUP BY t.phone
HAVING IFNULL(SUM(t.status IN ('NI','SALE','B')),0) = 0
答案 1 :(得分:3)
SELECT DISTINCT phone
FROM yourtable AS a
WHERE NOT EXISTS (SELECT 1
FROM yourtable AS b
WHERE a.phone = b.phone
AND b.status in ('NI', 'SALES', 'B'));
这具有额外的好处,即假设手机上有一个索引,它将始终使用索引。
答案 2 :(得分:2)
不确定你想要的逻辑。
在这里,我会找到没有NI
,没有SALES
且没有B
的电话。
SELECT phone
FROM my_table
GROUP BY phone
HAVING COUNT(CASE WHEN status = 'NI' THEN 1 END) = 0
AND COUNT(CASE WHEN status = 'SALES' THEN 1 END) = 0
AND COUNT(CASE WHEN status = 'B' THEN 1 END) = 0
答案 3 :(得分:0)
我通过更新Query
PROPER QUERY
SELECT DISTINCT(phone) FROM my_table WHERE status NOT IN ('NI','SALE','B') AND status IN ('DROP')
以上query
对我有用,执行时间也减少了。