[英]How to use GROUP BY syntax in this multi-JOIN statement with a CASE statement?
我有以下查詢
SELECT s.s_id, s.t_id, c.c_id, c.desc, sm.user_id
FROM s s
INNER JOIN c c
ON s.c_id=c.c_id
INNER JOIN sm sm
ON s.t_id = sm.t_id
WHERE s.c_id=8;
它返回以下結果集
s.s_id s.t_id c.c_id c.desc sm.user_id
3 123 8 something 2
3 123 8 something 2
3 123 8 something 1
4 456 8 something 2
4 456 8 something 2
我想要
CASE
語法) s.s_id
(這涉及使用GROUP BY s.s_id
) 例如,如果s.c_id=8
和sm.user_id=1
則結果集為
s.s_id s.t_id c.c_id c.desc sm.user_id does_user_own_product
3 123 8 something 1 yes
4 456 8 something 2 no
當s.s_id=3
, does_user_own_product
值為yes
因為至少有一個sm.user_id=1 WHERE s.s_id=3
。 當s.s_id=4
, does_user_own_product
值為no
因為在sm.user_id=1 WHERE s.s_id=4
的地方沒有sm.user_id=1 WHERE s.s_id=4
。
例如,如果s.c_id=8
和sm.user_id=2
則結果集為
s.s_id s.t_id c.c_id c.desc sm.user_id does_user_own_product
3 123 8 something 1 yes
4 456 8 something 2 yes
當s.s_id=3
, does_user_own_product
值為yes
因為至少有一個sm.user_id=2 WHERE s.s_id=3
。 當s.s_id=4
, does_user_own_product
值為yes
因為至少有一個sm.user_id=2 WHERE s.s_id=4
。
給定我提供s.c_id
和sm.user_id
的值,實現上述兩個子集的適當查詢是什么sm.user_id
編輯我意識到對於用戶擁有產品意味着什么有些困惑。
如果可以在sm.user_id中找到用戶的ID,則該用戶擁有該s.s_id
因此,例如,在原始結果集中
s.s_id s.t_id c.c_id c.desc sm.user_id
3 123 8 something 2
3 123 8 something 2
3 123 8 something 1
4 456 8 something 2
4 456 8 something 2
用戶1和2擁有s.s_id 3,只有用戶2擁有s.s_id 4
這樣做: http : //www.sqlfiddle.com/#!2/e4c84/21
利用MySql的優勢:
set @userInquired := 1;
select s_id, t_id, c_id, dsc,
bit_or(user_id = @userInquired) as does_user_own_product
from tbl
group by s_id;
set @userInquired := 2;
select s_id, t_id, c_id, dsc,
bit_or(user_id = @userInquired) as does_user_own_product
from tbl
group by s_id;
公分母SQL:
set @userInquired := 1;
select s_id, t_id, c_id, dsc,
case when sum(case when user_id = @userInquired then 1 end) > 0 then
1
else
0
end as does_user_own_product
from tbl
group by s_id;
set @userInquired := 2;
select s_id, t_id, c_id, dsc,
case when sum(case when user_id = @userInquired then 1 end) > 0 then
1
else
0
end as does_user_own_product
from tbl
group by s_id;
公用分母SQL。 如果您的數據庫沒有正確的布爾值,這是最短的方法,請使用case when
和max
的case when
組合:
set @userInquired := 1;
select s_id, t_id, c_id, dsc,
max(case when user_id = @userInquired then 1 else 0 end)
as does_user_own_product
from tbl
group by s_id;
set @userInquired := 2;
select s_id, t_id, c_id, dsc,
max(case when user_id = @userInquired then 1 else 0 end)
as does_user_own_product
from tbl
group by s_id;
也許是這樣的:
SELECT s.s_id, s.t_id, c.c_id, c.desc, sm.user_id, MAX(sm.user_id = @userid) AS does_user_own_product
FROM s s
INNER JOIN c c
ON s.c_id=c.c_id
INNER JOIN sm sm
ON s.t_id = sm.t_id
WHERE s.c_id=8
GROUP BY s.s_id;
雖然,老實說,盡管我看不出在既不包含在GROUP BY中也不在聚合中的拉列(如c.c_id
, c.desc
, sm.user_id
)沒有多大意義。 (是的,MySQL確實允許您執行此操作,但是在您的情況下,這些值似乎沒有多大意義。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.