所以我有这张表A:
color ID MODEL
-----------------------------
red | 10 | HONDA
blue | 10 | TOYOTA
red | 15 | ISUZU
red | 30 | MITSUBISHI
red | 5 | HONDA
blue | 5 | SUBARU
orange | 10 | HYUNDAI
black | 40 | CHRYSLER
我希望得到彼此不具有相同身份的所有红色和蓝色
所以我的预期结果是:
color ID
------------
red | 15
red | 30
答案 0 :(得分:1)
或使用anti join
select t1.color, t1.id
from
tableA t1
left outer join
tableA t2 on t2.id = t1.id and t2.color != t1.color
where
t1.color in ('red', 'blue')
and t2.color is null
答案 1 :(得分:0)
像这样的东西
SELECT *
FROM yourtable
WHERE id IN (SELECT id
FROM youtable
GROUP BY id
HAVING Count(case when color IN ( 'red', 'blue' ) then 1 end) = 1)
答案 2 :(得分:0)
使用NOT EXISTS
查找ID匹配但颜色不同的行:
select *
from yourtable a
where a.color IN ('red', 'blue')
and not exists (
select 1
from yourtable b
where a.id = b.id
and b.color NOT IN ('red', 'blue')
)
注意:
color
表格答案 3 :(得分:0)
我认为你的预期结果应该是红色15.红色30不符合条件,因为黄色30,它们具有相同的ID。看看我的代码:
SELECT t.id, t.color
FROM t
INNER JOIN
(SELECT id
FROM t
GROUP BY id
HAVING COUNT(*) = 1) sub
ON t.id = sub.id
WHERE color = 'red'
OR color = 'blue'
答案 4 :(得分:0)
删除了上一个答案。经过测试,它正在运行。
WITH tbl
AS (SELECT
color,
id
FROM TABLE1
WHERE color IN ('red', 'blue')
)
SELECT
t1.color,
t1.id
FROM tbl t1
LEFT JOIN tbl t2
ON t1.id = t2.id
AND t1.color <> t2.color
WHERE t1.id IS NULL
OR t2.id IS NULL
答案 5 :(得分:0)
此查询返回COLOR为红色或蓝色但不是两者的所有ID。
select id , color
from your_table
where color in ('red', 'blue')
and id in (
select id
from your_table
where color in ('red', 'blue')
group by id
having count(*) = 1)