Mysql - 如何根据特定条件从两个表中检索字段?

时间:2012-06-06 12:27:37

标签: php mysql select join

我正在尝试从一个表中检索post_id,post_year,post_desc,post_title,post_date,从另一个表中检索img_filename,其中post_id相等,其中is_thumb为1(其中我选择该图像作为帖子缩略图)

据我所知,没有运气:

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

由于

3 个答案:

答案 0 :(得分:2)

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

或者,如果您更喜欢USING语法,

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

不同之处在于第一个查询从两个表中返回post_id,您需要对其进行别名。

答案 1 :(得分:2)

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

答案 2 :(得分:0)

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;

如果img_is_thumb为1,它将返回img_filename,否则它将返回null。