簡體   English   中英

如何從與外鍵鏈接的兩個表中選擇不同的行

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

我想顯示數據庫中的圖像。我有兩個表gallery_photos

gallery_category 在此處輸入圖片說明

我想顯示任何帶有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

您可以按分組方式進行分組

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

使用“左聯接”將所有行保留在左表中。

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

看一下這個!

INNER JOIN,LEFT JOIN,RIGHT JOIN和FULL JOIN有什么區別?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM