收藏夹离开加入

时间:2014-04-24 12:27:37

标签: mysql left-join

我有一个可以看到场地的网站。当您单击一个场地时,它会显示一个弹出窗口。有一个喜欢的按钮,可以激活或不激活。此代码在此弹出窗口的ajax中

SELECT * FROM venue_datetime
LEFT JOIN venue_calendar ON venue_datetime.calendar = venue_calendar.calendar_id
LEFT JOIN venue_events ON venue_calendar.event = venue_events.event_id
LEFT JOIN venue ON venue_events.venue = venue.venue_id
LEFT JOIN favorites ON venue.venue_id = favorites.favorites_venue_id OR venue.venue_id is null
LEFT JOIN users ON favorites.favorites_user_id = users.id OR favorites.favorites_user_id is null
WHERE datetime_id = ? AND id = ?

此部分无法按预期工作。

LEFT JOIN favorites ON venue.venue_id = favorites.favorites_venue_id OR venue.venue_id is null
LEFT JOIN users ON favorites.favorites_user_id = users.id OR favorites.favorites_user_id is null

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

基于评论

SELECT * FROM venue_datetime
LEFT JOIN venue_calendar ON venue_datetime.calendar = venue_calendar.calendar_id
LEFT JOIN venue_events ON venue_calendar.event = venue_events.event_id
LEFT JOIN venue ON venue_events.venue = venue.venue_id
LEFT JOIN favorites ON venue.venue_id = favorites.favorites_venue_id 
LEFT JOIN users ON favorites.favorites_user_id = users.id 
WHERE datetime_id = ? AND (users.id = ? or users.id is null)

OR

SELECT * FROM venue_datetime
LEFT JOIN venue_calendar ON venue_datetime.calendar = venue_calendar.calendar_id
LEFT JOIN venue_events ON venue_calendar.event = venue_events.event_id
LEFT JOIN venue ON venue_events.venue = venue.venue_id
LEFT JOIN favorites ON venue.venue_id = favorites.favorites_venue_id 
LEFT JOIN users ON favorites.favorites_user_id = users.id 
  AND users.id = ?
WHERE datetime_id = ? 

使用外连接时,条件必须考虑空值。因此,连接必须处理的连接必须从不返回所有值的表中为空,或者您必须在连接本身上设置限制条件。

答案 1 :(得分:1)

假设用户总是在那里,那么也许这样做: -

SELECT * 
FROM venue_datetime
INNER JOIN users ON users.id = ?
LEFT JOIN venue_calendar ON venue_datetime.calendar = venue_calendar.calendar_id
LEFT JOIN venue_events ON venue_calendar.event = venue_events.event_id
LEFT JOIN venue ON venue_events.venue = venue.venue_id
LEFT JOIN favorites ON venue.venue_id = favorites.favorites_venue_id AND favorites.favorites_user_id = users.id 
WHERE datetime_id = ? 

仅根据用户ID将用户加入场地,然后根据场地和用户加入收藏夹。