我有两张桌子。一个是新闻,第二个是图像。每个新闻可以有0-3个图像(image_1,image_2,表新闻中的image_3 - 其ID)。现在我试图从图像表中获取所有行,但它只给了我一个。
就像那样(但它不起作用)
select news.id as nid, image_1, image_2, image_3, photos.id as pid, big, small
from news
left join photos
on image_1=photos.id, image_2=photos.id, image_3=photos.id
order by nid desc
答案 0 :(得分:1)
即使@juergen提出了更好的选择,并指导您如何以您的方式解决您的问题,但如果您面临问题该怎么办,那么您可以按照以下查询 -
SELECT p.id AS pid, n1.image_1, n2.image_2, n3.image_3, big, small
FROM photos AS p
LEFT JOIN news AS n1 ON n1.image_1=p.id
LEFT JOIN news AS n2 ON n2.image_2=p.id
LEFT JOIN news AS n3 ON n1.image_3=p.id
ORDER BY n.id DESC;
答案 1 :(得分:0)
您必须使用不同的别名加入photos
表3次。
但实际上你应该改变你的桌面设计。添加另一个名为news_photos
news_photos table
-----------------
news_id
photo_id
然后,您可以从image
表中删除news
列。
更改后,您可以选择包含所有类似照片的新闻
select n.*, p.name
from news
left join news_photos np on n.id = np.news_id
left join photos p on p.id = np.photo_id
where n.id = 1234