[英]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) 我正在尝试从一个表中检索post_id,post_year,post_desc,post_title,post_date和从另一个表中检索img_filename,其中post_id相等且is_thumb为1(我选择该图像作为帖子缩略图)
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, 或者,如果您喜欢
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
The difference is that the first query returns post_id
from both tables and you need to alias it. 不同之处在于,第一个查询从两个表中都返回
post_id
,因此您需要对其进行别名化。
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. 如果img_is_thumb为1,它将返回img_filename,否则将返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.