![](/img/trans.png)
[英]How to compare fields in a row in two tables and return values that are not the same
[英]Compare two values in a row
select event_slots.id as event_slot_id, u.first_name, u.id AS user_id,
sum(case when next_round = 1 then 1 else 0 end) AS yes,
sum(case when next_round = 2 then 1 else 0 end) AS no
from event_slots
left join users as u on u.id = event_slots.selected_by_user_id
left join audition_card_values as acv on acv.user_id = event_slots.selected_by_user_id
where
event_id = 1 and
selected_by_user_id is not null
group by acv.user_id
厄格布尼斯:
现在我只需要第一行“first_name”=“Eins”,因为“yes”等于“no”。 我怎样才能做到这一点? WHERE 是 = 否...不起作用。
谢谢你的帮助
我会将查询表述为:
select
ev.id as event_slot_id,
u.first_name,
u.id AS user_id,
sum(next_round = 1) AS yes,
sum(next_round = 2) AS no
from event_slots as ev
inner join audition_card_values as acv
on acv.user_id = ev.selected_by_user_id
left join users as u
on u.id = ev.selected_by_user_id
where e.event_id = 1
group by ev.id, u.first_name, u.id
having sum(next_round = 1) = sum(next_round = 2)
理由:
sum()
中的条件表达式可以简化
您可以使用having
子句进行过滤; MySQL 还支持在having
子句中重用select
子句中定义的别名,因此您可以拼写为:have having yes = no
- 但我更喜欢重复条件表达式,因为这是标准 Z9778840A0100CB30C9828ZB7412
audition_card_values
上的left join
后跟where... is not null
可以重写为简单的inner join
我固定了你的group by
条款; select
子句中的每个非聚合列都必须出现在group by
子句中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.