简体   繁体   English

如何从与外键链接的两个表中选择不同的行

[英]how to select distinct rows from two tables linked with foreign key

I want to show images from database.I have two tables gallery_photos 我想显示数据库中的图像。我有两个表gallery_photos

gallery_category gallery_category 在此处输入图片说明

I want to show any photos_filename with category_name. 我想显示任何带有category_name的photos_filename。 photo_category is the foreign key of category_id photo_category是category_id的外键

mysql query i wrote 我写的mysql查询

SELECT distinct a.category_name
       ,b.photo_filename 
FROM gallery_category a  
inner join gallery_photos b  on (a.category_id=b.photo_category)

please help me to do that... 请帮助我做到这一点...

i want to select exactly like this 我想选择完全像这样

albums/1456226111.jpg interior
albums/1456226239.jpg graphics
albums/1456226339.jpg random
albums/1456226478.jpg goods

you can grouping it by group by 您可以按分组方式进行分组

SELECT a.category_name,b.photo_filename 
FROM gallery_category a  JOIN gallery_photos b  
ON a.category_id=b.photo_category 
GROUP BY a.category_name

Use Left join to keep all the rows in the left table. 使用“左联接”将所有行保留在左表中。

SELECT 
  b.photo_filename, 
  a.category_name 
FROM 
  gallery_category a  LEFT join gallery_photos b  ON (a.category_id=b.photo_category)

check this out! 看一下这个!

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN? INNER JOIN,LEFT JOIN,RIGHT JOIN和FULL JOIN有什么区别?

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

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