2016-09-14 54 views
1

所以我有此表中犯規的比賽DATAS:如何選擇另一列

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 

我想獲得的所有紅色和不具有相同的ID相互

藍色

所以我預期的結果是:

color ID 
------------ 
red | 15 
red | 30 
+0

但還有另外30 ...黃色 – kbball

+0

@robin - 檢查所有的答案,並提到什麼不適合你。 – Utsav

+0

Hi @Utsav!當我嘗試你的代碼時,它不包括紅色的30,因爲我有一個黃色的30你能幫助我嗎? –

回答

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) 
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
+0

Hi @kamil g!當我嘗試你的代碼時,它不包含紅色30因爲我有一個黃色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 
+0

Hi @schurik!當我嘗試你的代碼時,它不包括'紅色30'因爲我有一個'黃色30'你能幫我這個嗎? –

+0

你想「**得到所有紅色和藍色,與另一種顏色沒有相同的標識**」爲什麼要包含紅色30? – schurik

+0

編輯我的帖子。這個問題有點讓我感到困惑。我想要得到所有紅色和藍色,沒有相同的ID –

0

我覺得你預期的結果應該只是紅色的,因爲黃30,這股相同的ID 15紅30將沒有資格。查看我的代碼:

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' 
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 
0

該查詢返回所有顏色爲紅色或藍色但不是兩者的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)