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
3条答案
按热度按时间6jjcrrmo1#
这就是我想到的:
sxpgvts32#
我们可以尝试以下查询来查找
id
有两个位置:找到那些
id
只有位置的A
:上面的查询是这样写的,以便我们可以在上面放置索引
(id, location)
. mysql应该能够利用这个索引进行两个查询。nfs0ujit3#
获取两个位置的ID
获取唯一ID