[英]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.