答案 0 :(得分:3)
要获取两个位置的ID
select id
from your_table
where location in ('A','B')
group by id
having count(distinct location) = 2
要获取唯一的ID
select id
from your_table
group by id
having count(distinct location) = 1
答案 1 :(得分:3)
我们可以尝试以下查询来找到同时具有两个位置的id
:
SELECT id
FROM yourTable
WHERE location IN ('A', 'B')
GROUP BY id
HAVING MIN(location) <> MAX(location);
要查找仅具有位置id
的{{1}}:
A
上面的查询是这样写的,以便我们可以在SELECT id
FROM yourTable
GROUP BY id
HAVING MIN(location) = MAX(location) AND MIN(location) = 'A';
上放置索引。 MySQL应该能够在两个查询中都利用该索引。
答案 2 :(得分:-1)
这是我想出的:
SELECT unique_id
,count(unique_id)
FROM (
SELECT a.id AS locationA
,b.id AS locationB
,CASE WHEN locationA IS NULL THEN 'onlyb' WHEN locationB IS NULL THEN 'onlya' ELSE 'both' END AS unique_id
FROM (
SELECT DISTINCT id
,location
FROM table
WHERE 1 = 1
AND location = 'A'
) a
FULL JOIN (
SELECT DISTINCT id
,location
FROM table
WHERE 1 = 1
AND location = 'B'
) b ON a.id = b.id
)
GROUP BY id