简体   繁体   中英

mysql LEFT JOIN: join table if value exists in column or if value does not exist use 'null'

I am using this query to join to return user_id and prod_id. If prod_id exists than the result should print with the user_id and the prod_id. However, if the prod_id does not exist null should be printed. But when I use the below query it only prints the two columns if values exists for both user_id and prod_id if prod_id does not exist it returns blank. Please help

SELECT DISTINCT A.wishlist_id, B.prod_id
FROM  wp_yith_wcwl A
LEFT JOIN  wp_yith_wcwl B ON A.user_id=B.user_id
WHERE A.user_id =5
AND B.prod_id=101424 

You are negating your outer join . You need to move the where criteria to the on of the join :

SELECT DISTINCT A.wishlist_id, B.prod_id
FROM  wp_yith_wcwl A
    LEFT JOIN  wp_yith_wcwl B ON A.user_id=B.user_id
        AND B.prod_id=101424 
WHERE A.user_id =5

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