我想從有兩個節目「籃球」和「足球」如何選擇的ID有一組所有值的行
給定一個表像這樣行的表中選擇所有編號:
Id program
1 basketball
2 football
3 basketball
2 basketball
1 football
4 football
5 basketball
我怎樣才能得到這樣的結果:
id
1
2
我想從有兩個節目「籃球」和「足球」如何選擇的ID有一組所有值的行
給定一個表像這樣行的表中選擇所有編號:
Id program
1 basketball
2 football
3 basketball
2 basketball
1 football
4 football
5 basketball
我怎樣才能得到這樣的結果:
id
1
2
既然你想返回有兩個值的id
的football
和basketball
,可以使用以下方法得出結果:
select id
from yt
where program in ('basketball', 'football')
group by id
having count(distinct program) = 2;
由於也可以通過多次加入你的桌子上完成的:
select t1.id
from yt t1
inner join yt t2
on t1.id = t2.id
where t1.program = 'basketball'
and t2.program = 'football';
+1不錯的查詢,不錯的演示和快速! – Bohemian 2013-04-24 13:38:56
您可以IN
或OR
語法做到這一點:
SELECT id
FROM table
WHERE program = 'basketball'
OR program = 'football';
如果你想只能得到前兩個結果,最後加LIMIT 2
。
順便說一句,如果沒有主鍵的表是非常糟糕的做法,那麼就沒有辦法爲這個表編制索引,因此性能會很差。
我不認爲這是OP正在尋找... – 2013-04-24 13:41:35
他可能正在尋找每個「程序」的第一個不同的結果。說實話,我認爲他應該修正他的表格,而不是重複'id's,這對於學習SQL而言可能比如何選擇不同的值(可以很容易地谷歌搜索)更重要。 – 2013-04-24 13:43:43
我覺得聚集是這個最普及的方法:
select id
from table
group by id
having sum(case when program = 'Football' then 1 else 0 end) > 0 and
sum(case when program = 'Basketball' then 1 else 0 end) > 0
的sum()
聲明都指望分別有「足球」和「籃球」的行數。當存在時,該數字大於0.
感謝這正是我正在尋找的! – 2013-04-24 17:06:12
SELECT 1 UNION SELECT 2 ;-) – Strawberry 2013-04-24 13:41:05
請問 - 您的ID有什麼問題?爲什麼有重複的價值觀? – 2013-04-24 13:41:55
我猜他們不是主鍵。 – 2013-04-24 13:42:41