简体   繁体   English

如何选择在另一列中不匹配的数据

[英]How to select datas that doesnt match in another column

So i have this table A:所以我有这张表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

i'd like to get all red and blue that does not have the same id with each other我想获得彼此不具有相同 ID 的所有红色和蓝色

So my expected result is:所以我的预期结果是:

color  ID
------------
red  | 15
red  | 30

or using an anti join或使用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

Something like this像这样的东西

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) 

Use NOT EXISTS to find rows with matching id but different colors:使用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')
    )

Notes:笔记:

  • for efficient lookup consider adding indexes ( more distinct values means higher efficiency of tree traversal )为了高效查找,请考虑添加索引(更多不同的值意味着更高的树遍历效率)
  • consider normalizing your data with additional dictionary color table考虑使用额外的字典color表标准化您的数据

I think your expected result should just be red 15. Red 30 would not qualify because of yellow 30, which shares the same id.我认为您的预期结果应该是红色 15。红色 30 不符合条件,因为黄色 30 具有相同的 ID。 Check out my code:看看我的代码:

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'

Removed the previous answer.删除了之前的答案。 Tested this and it is working.对此进行了测试,它正在工作。

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

This query returns all the IDs where the COLOR is red or blue but not both.此查询返回 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM