2

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

这是我没有运气的情况:

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

谢谢

4

3 回答 3

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从两个表中返回,您需要为它取别名。

于 2012-06-06T12:29:05.750 回答
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
于 2012-06-06T12:29:30.287 回答
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。

于 2012-06-06T12:37:44.247 回答