简体   繁体   中英

Mysql - How to retrieve fields from two tables based on certain criteria?

I am trying to retrieve post_id, post_year, post_desc, post_title, post_date from one table and img_filename from another table where the post_id is equal and where is_thumb is 1 (where i have chosen that image as the posts thumbnail)

This is as far as I have got without luck:

SELECT post_id, post_year, post_desc, post_title, post_date,
FROM mjbox_posts
JOIN mjbox_images
USING (img_is_thumb)
WHERE img_is_thumb = 1
AND mjbox_images.post_id = mjbox_posts.post_id

Thanks

SELECT  p.post_id, post_year, post_desc, post_title, post_date, img_filename
FROM    mjbox_posts p
JOIN    mjbox_images i
ON      i.post_id = p.post_id
        AND i.img_is_thumb = 1

or, if you prefer USING syntax,

SELECT  post_id, post_year, post_desc, post_title, post_date, img_filename
FROM    mjbox_posts p
JOIN    mjbox_images i
USING   (post_id)
WHERE   i.img_is_thumb = 1

The difference is that the first query returns post_id from both tables and you need to alias it.

SELECT post_id, post_year, post_desc, post_title, post_date,
FROM mjbox_posts
INNER JOIN mjbox_images on mjbox_images.post_id = mjbox_posts.post_id
WHERE img_is_thumb = 1
SELECT post_id, post_year, post_desc, post_title, post_date, if(img_is_thumb, img_filename, null)
FROM mjbox_posts a,
mjbox_images b
WHERE a.post_id= b.post_id;

It will return img_filename if img_is_thumb is 1, else it will return null.

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