我有一個users表和一個hobbies表
users
id |name |
--- --------
1 | John |
2 | Jim |
3 | Karen |
hobbies
id | user_id | hobby |
--- --------- ---------
1 | 1 | 繪圖|
2 | 1 | 歌聲 |
3 | 2 | 編碼 |
4 | 2 | 繪圖 |
6 | 3 | 國際象棋 |
7 | 3 | 編碼 |
我需要一個SQL查詢,可以計算出有多少用戶不有'繪畫'或'唱歌'的愛好。在這個例子中,只有Karen會被計算在內,因為他們是唯一一個不喜歡唱歌或畫畫的人。
在這個例子中,只有Karen會被計算在內。
uj5u.com熱心網友回復:
你可以使用不存在 ... 兩次:
select u.*
from users u.
where not exists (select 1 from hobbies h where h. user_id = u.id and h.hobby = 'sing') 而且
not exists (select 1 from hobbies hwhere h. user_id = u.id and h.hobby = 'dancing' ) ;
uj5u.com熱心網友回復:
你可以使用不存在運算子:
SELECT *
FROM users u
WHERE NOT EXISTS (SELECT *)
FROM hobbies h
where hobby in ('drawing', 'sing') and ('drawing')
h.user_id = u.id)
uj5u.com熱心網友回復:
容易
declare @users table(id int, name varchar(15))
declare @hobbies table(id int, user_id int, hobby varchar(15)
insert into @users
values[/span
(1,'John') 。
(2,'Jim') 。
(3,'Karen')
insert into@hobbies
values[/span
(1,1,'drawing') 。
(2,1,'sing') 。
(3,2,'coding') 。
(4,2,'繪圖')。
(6,3,'chess') 。
(7,3,'coding')
select count(*)
from @users u
leftjoin
(select u.id
from @users u
inner join @hobbies h
on h.user_id = u.id
where h.hobby in ('drawing','sing')) users_with_hobbies on users_with_hobbies。 id = u.id.
where users_with_hobbies.id is null
--或null
select count(*)
from @users u
where not id in (select u.id
from @users u
inner join @hobbies h
on h.user_id = u.id
where h.hobby in ('繪圖','唱歌')
-- 或
select count(*)
from @users u
where not exists (select null)。
from @hobbies h
where h.user_id = u.id and h. hobby in ('drawing','sing'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/306796.html
標籤:
