简体   繁体   中英

Mysql - Left join issues in the where clause

I have two tables : activities and activity_images and the foreign key constraint is :

activities.id = activitiy_images.activity_id

Now some activities have images and some do not, which means for a particular activities.id , there might not be an entry on activity_images.

i want to fetch all the data by default , regardless of the data present in activity_images .

Below is my query :

select a.*,a.id as 'activity_id',b.* 
   from activities a 
   left join activity_images b on a.id = b.activity_id 
   where b.image_type='main' LIMIT 0, 9

The issue is with the output . The above query only gives me the data for the matching rows and where b.image_type='main'. It does not output the rows for which there is no entry in activity_images .

I want all the rows but at the same time i want to make sure that b.image_type='main' because there are other values for image_type and i just want to grab the values for image_type= 'main' (If at all there is a match) .

Please advice . Thanks in advance.

select a.*,a.id as 'activity_id',b.* 
   from activities a 
   left join activity_images b on a.id = b.activity_id 
   where b.image_type='main' OR b.image_type IS NULL
 LIMIT 0, 9

Would this do what you want?

I would recommend image_type to be a not null column in this case otherwise you could get data that has a matching row but image_type is actually set to null.

Try a subquery. This will pre-select only the rows in your activity images table with your preferred image type, and will still select everything from your activities table:

SELECT a.*,b*
FROM activities a 
    LEFT JOIN (
        SELECT * FROM activity_images WHERE image_type = 'main'
    ) b ON a.id = b.activity_id;
SELECT * FROM activity_images WHERE image_type = 'main' a;

When criteria in a WHERE clause applies to a joined table, it's basically treated as an INNER JOIN .

The proper way to handle this is to move the criteria into the ON clause:

SELECT a.*, a.id as 'activity_id', b.* 
   FROM activities a 
   LEFT JOIN activity_images b
     ON b.activity_id = a.id
     AND b.image_type = 'main'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM