使用left join和where子句进行sql查询

时间:2014-02-27 17:56:41

标签: mysql sql select left-join

我有以下查询

SELECT *
  FROM tbl_events AS event
       LEFT JOIN tbl_business_events AS bevent 
                 ON event.event_id = bevent.event_id 
       LEFT JOIN tbl_business_sector AS bsec 
                 ON event.event_id = bsec.event_id 
       LEFT JOIN tbl_sectors AS sector 
                 ON bsec.sector_id = sector.sector_id 
       LEFT JOIN tbl_event_location AS eloc 
                 ON event.event_id = eloc.event_id 
       LEFT JOIN tbl_locations AS location 
                 ON location.location_id = eloc.location_id 
 WHERE event.event_type = 1

我用它来提取我的事件列表的所有细节,这是有效的,但我现在想要从另一个表tbl_event_images中提取事件配置文件图片。此表存储了所有事件图像,但有一个名为is_profile_picture的字段,用于确定是否为配置文件pic(如果图像是配置文件图片,则值为0表示不是,如果图像是配置文件图片,则为1)

所以我尝试了以下查询以使用以下查询获取事件概要图片以及其他信息

SELECT *
  FROM tbl_events AS event
       LEFT JOIN tbl_event_images AS eIMG 
                 ON event.event_id = eIMG.event_id
       LEFT JOIN tbl_business_events AS bevent 
                 ON event.event_id = bevent.event_id
       LEFT JOIN tbl_business_sector AS bsec 
                 ON event.event_id = bsec.event_id
       LEFT JOIN tbl_sectors AS sector 
                 ON bsec.sector_id = sector.sector_id
       LEFT JOIN tbl_event_location AS eloc 
                 ON event.event_id = eloc.event_id
       LEFT JOIN tbl_locations AS location 
                 ON location.location_id = eloc.location_id
 WHERE event.event_type =1

但是此查询会为该事件在该表中的每张照片返回一个新行。

所以我接着尝试在上面添加另一个where子句     AND eIMG.is_profile_picture =1

但是因为并非每个商家信息都有照片,更不用说个人资料图片,因此上述查询只会返回包含个人资料照片的事件。

我怎样才能为每个事件返回1行,无论他们是否有个人资料图片?如果他们这样做,那么它将添加图像的名称,如果它没有将它设置为NULL

由于 路加

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT *
FROM tbl_events AS event
LEFT JOIN tbl_event_images AS eIMG ( ON event.event_id = eIMG.event_id AND  eIMG.is_profile_picture = 1 )
LEFT JOIN tbl_business_events AS bevent ON event.event_id = bevent.event_id
LEFT JOIN tbl_business_sector AS bsec ON event.event_id = bsec.event_id
LEFT JOIN tbl_sectors AS sector ON bsec.sector_id = sector.sector_id
LEFT JOIN tbl_event_location AS eloc ON event.event_id = eloc.event_id
LEFT JOIN tbl_locations AS location ON location.location_id = eloc.location_id
WHERE event.event_type =1

答案 1 :(得分:1)

而不是使用WHERE条件,将is_profile_picture条件添加到您的JOIN条件中:

SELECT *
FROM tbl_events AS event
LEFT JOIN tbl_event_images AS eIMG 
   ON   event.event_id = eIMG.event_id 
    AND eIMG.is_profile_picture =1
LEFT JOIN tbl_business_events AS bevent 
   ON event.event_id = bevent.event_id
LEFT JOIN tbl_business_sector AS bsec 
   ON event.event_id = bsec.event_id
LEFT JOIN tbl_sectors AS sector 
   ON bsec.sector_id = sector.sector_id
LEFT JOIN tbl_event_location AS eloc 
   ON event.event_id = eloc.event_id
LEFT JOIN tbl_locations AS location 
   ON location.location_id = eloc.location_id
WHERE event.event_type =1

WHERE会过滤所有结果,在这种情况下会有效地否定您对LEFT JOIN的使用。添加到JOIN条件本身意味着只会加入一些图片,但仍会返回原始查询的所有结果。