查询以获取仅位于一个位置或同时位于两个位置的ID

vwkv1x7d  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(561)

如何从这个简单的表中获取同时位于位置a和b或仅位于位置a或b的ID

结果示例:a22对于位置a是唯一的,只有a23同时位于a和b等位置。

6jjcrrmo

6jjcrrmo1#

这就是我想到的:

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
sxpgvts3

sxpgvts32#

我们可以尝试以下查询来查找 id 有两个位置:

SELECT id
FROM yourTable
WHERE location IN ('A', 'B')
GROUP BY id
HAVING MIN(location) <> MAX(location);

找到那些 id 只有位置的 A :

SELECT id
FROM yourTable
GROUP BY id
HAVING MIN(location) = MAX(location) AND MIN(location) = 'A';

上面的查询是这样写的,以便我们可以在上面放置索引 (id, location) . mysql应该能够利用这个索引进行两个查询。

nfs0ujit

nfs0ujit3#

获取两个位置的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

相关问题