如何从与外键

时间:2016-02-24 09:56:36

标签: mysql

我想从数据库中显示图像。我有两个表 gallery_photos

gallery_category enter image description here

我想用category_name显示任何photos_filename。 photo_category是category_id的外键

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)

请帮我这样做......

我想选择与此类似的

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

2 个答案:

答案 0 :(得分:2)

您可以按小组对其进行分组

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

答案 1 :(得分:1)

使用左连接保留左表中的所有行。

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

检查一下!

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?