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

时间:2018-12-05 13:25:41

标签: mysql sql

我如何从这个简单的表中获得既位于位置A又位于位置B或仅位于位置A或B中的ID

enter image description here

示例结果: a22仅对于位置A是唯一的 A23在A和B中 等

3 个答案:

答案 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