两个 select 的交集
Intersection of two select
我有这个 table :
+----+-----------+-------+
| id | client_id | is_in |
+----+-----------+-------+
| 1 | 1 | 0 |
+----+-----------+-------+
| 2 | 2 | 0 |
+----+-----------+-------+
| 3 | 1 | 1 |
+----+-----------+-------+
| 4 | 2 | 1 |
+----+-----------+-------+
| 5 | 3 | 1 |
+----+-----------+-------+
| 6 | 3 | 1 |
+----+-----------+-------+
| 7 | 1 | 0 |
+----+-----------+-------+
| 8 | 4 | 0 |
+----+-----------+-------+
| 9 | 4 | 0 |
+----+-----------+-------+
而且我需要至少一次获得 'is_in' 等于 1 且从未 'is_in' 等于 0 的客户数量(在本例中是 client_id 3).
为此,我进行了两次查询:
SELECT client_id FROM foo WHERE is_in = 1;
和
SELECT client_id FROM foo WHERE is_in = 0;
我计划在它们之间创建一个 INTERSECT,这样我就可以获得两个选择之间的公共条目,所以我只需要执行 "number of clients with is_in = 1" - "count(of the result of the intersect)".
但是 INTERSECT 不能与 MYSQL 一起使用,在这种情况下是否有替代 INTERSECT 的方法或更简单的方法来获得我需要的东西(我觉得我做的很复杂一无所有)。
谢谢。
SELECT id, client_id FROM foo WHERE is_in = 1 AND client_id NOT IN (SELECT client_id FROM foo WHERE is_in = 0)
或者,如果您只需要客户编号:
SELECT DISTINCT client_id FROM foo WHERE is_in = 1 AND client_id NOT IN (SELECT client_id FROM foo WHERE is_in = 0)
您可以对它们求和并获得最小值,按客户端 ID 分组,并使结果排除任何具有零的值。试试这个:
SELECT COUNT(client_id)
FROM foo
GROUP BY client_id
HAVING SUM(is_in) > 0 && MIN(is_in) > 0
我有这个 table :
+----+-----------+-------+
| id | client_id | is_in |
+----+-----------+-------+
| 1 | 1 | 0 |
+----+-----------+-------+
| 2 | 2 | 0 |
+----+-----------+-------+
| 3 | 1 | 1 |
+----+-----------+-------+
| 4 | 2 | 1 |
+----+-----------+-------+
| 5 | 3 | 1 |
+----+-----------+-------+
| 6 | 3 | 1 |
+----+-----------+-------+
| 7 | 1 | 0 |
+----+-----------+-------+
| 8 | 4 | 0 |
+----+-----------+-------+
| 9 | 4 | 0 |
+----+-----------+-------+
而且我需要至少一次获得 'is_in' 等于 1 且从未 'is_in' 等于 0 的客户数量(在本例中是 client_id 3).
为此,我进行了两次查询:
SELECT client_id FROM foo WHERE is_in = 1;
和
SELECT client_id FROM foo WHERE is_in = 0;
我计划在它们之间创建一个 INTERSECT,这样我就可以获得两个选择之间的公共条目,所以我只需要执行 "number of clients with is_in = 1" - "count(of the result of the intersect)".
但是 INTERSECT 不能与 MYSQL 一起使用,在这种情况下是否有替代 INTERSECT 的方法或更简单的方法来获得我需要的东西(我觉得我做的很复杂一无所有)。
谢谢。
SELECT id, client_id FROM foo WHERE is_in = 1 AND client_id NOT IN (SELECT client_id FROM foo WHERE is_in = 0)
或者,如果您只需要客户编号:
SELECT DISTINCT client_id FROM foo WHERE is_in = 1 AND client_id NOT IN (SELECT client_id FROM foo WHERE is_in = 0)
您可以对它们求和并获得最小值,按客户端 ID 分组,并使结果排除任何具有零的值。试试这个:
SELECT COUNT(client_id)
FROM foo
GROUP BY client_id
HAVING SUM(is_in) > 0 && MIN(is_in) > 0