[英]MySQL LEFT JOIN is returning just one row with a where condition on the right table
I have two tables, one with events and a second one with events marked as saved by a user. 我有两个表,一个表带有事件,第二个表带有标记为用户保存的事件。
I need to get all the events, and for a certain user to know whether an event is saved or not. 我需要获取所有事件,并让某个用户知道是否保存了事件。
For doing that I am using this SQL 为此,我正在使用此SQL
SELECT event.id, saved.user_id
FROM event
LEFT JOIN saved on event.id = saved.event_id
but then I am getting repeated events, as one event may be marked as saved by many users at the saved table. 但是随后我得到了重复的事件,因为在保存的表中一个事件可能被许多用户标记为已保存。
Therefore I've added a where condition as 因此,我添加了where条件作为
SELECT event.id, saved.user_id
FROM event
LEFT JOIN saved on event.id = saved.event_id
where saved.user_id = "71"
but surprisingly, the result obtained is reduced to just one row, when I was expecting thousands of them, most of them with saved.user_id to null and only a few or just once with saved.user_id = 71 但是令人惊讶的是,当我期望成千上万的结果时,获得的结果减少到只有一行,其中大多数将save.user_id设置为null,而使用save.user_id = 71则只有很少或只有一次
Ideally I would like to have true/false at the saved.user_id column for a certain user, eg: 71 理想情况下,我希望某个用户的saved.user_id列为true / false,例如:71
What is wrong here? 怎么了
Change: 更改:
LEFT JOIN saved on event.id = saved.event_id
where saved.user_id = "71"
To: 至:
LEFT JOIN saved on event.id = saved.event_id
and saved.user_id = "71"
Or: 要么:
LEFT JOIN saved on event.id = saved.event_id
WHERE saved.user_id = "71" OR saved.user_id IS NULL
The where
clause filters data from all tables, the on
clause just filters the rows from the right-hand table. where
子句过滤所有表中的数据, on
子句仅过滤右侧表中的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.