简体   繁体   English

MySQL在两个表之间的多重连接

[英]Mysql multiple join between two tables

I have got two tables. 我有两张桌子。 One is for news and second one for images. 一种是新闻,另一种是图像。 Each news can have 0-3 images (image_1, image_2, image_3 in table news - its id). 每个新闻可以包含0-3张图片(表格新闻中的image_1,image_2,image_3-其ID)。 Now iam trying to get all rows from images table but its giving me back only one. 现在我试图从图像表中获取所有行,但它只给我回来。

Like that (but it is not working) 这样(但不起作用)

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

Even @juergen has suggested better option and also guided you how to solve your problem in your way but if stil you are facing issue how to do then you can follow below query- 甚至@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;

You have to join the photos table 3 times with different aliases. 您必须使用不同的别名加入photos表3次。

But you actually should rather change your table design. 但是您实际上应该更改表设计。 Add another table called news_photos 添加另一个名为news_photos

news_photos table
-----------------
news_id
photo_id

Then you can remove the image columns from the news table. 然后,您可以从news表中删除image列。

After the changes you can select news with all photos of like that 更改后,您可以选择包含所有此类照片的新闻

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM