连接-从一个表中获取行,然后在另一个表中获得匹配的所有行?但是第一个表匹配行不应该重复


Joins - get row from one table then get all rows that match in another table? but first table matching row should not be repeated

我有两个表。图库和连接。

Gallery
id | title
 1 | Dog Gallery
 2 | Cat Gallery
Joins
id | gallery_id | picture_id
 1 |      1     |     100
 2 |      1     |     101
 3 |      2     |     56
 4 |      1     |     102

我想得到id,画廊标题从画廊-其中id等于一个特定的id,但也得到所有的行从连接画廊id等于一个特定的画廊id。

如果id是1。我想要的狗画廊从画廊和图片id 100,101和102从连接。

现在的问题是画廊标题应该出现一次。结果是标题=狗画廊picture_id=100,标题=狗画廊picture_id=101,标题=狗画廊picture_id=102我需要这样的结果Title =dog gallery picture_id=100,picture_id=101 and picture_id=102

您可以使用GROUP_CONCAT将所有id作为字符串

SELECT G.*, GROUP_CONCAT(DISTINCT P.picture_id ORDER BY P.picture_id DESC SEPARATOR ',') 
FROM gallery as G
LEFT JOIN pictures as P ON P.gallery_id = G.id 
GROUP BY G.id;