从第三个 table 获取记录

Get records from third table

我有三个表,还有重复的列名 :) 我想将相册连接到产品,将图像连接到相册。图片很多。尝试这样的查询,它给了我重复的产品。是否有机会在一个查询中获取所有内容?

        SELECT
        *, p.name as nazwa, a.name as nazwa_al, i.name as obrazek
        FROM products p
        JOIN 
        albums a on p.album_id=a.id
        JOIN
          (SELECT *, images.name AS nazwa_im FROM images ORDER BY images.order ASC) i
        ON i.album_id=a.id
        ORDER BY p.order ASC

产品

+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| id          | int(11) | NO   | PRI | NULL    | auto_increment |
| name        | text    | NO   |     | NULL    |                |
| description | text    | NO   |     | NULL    |                |
| album_id    | int(11) | YES  |     | NULL    |                |
| order       | int(11) | NO   |     | NULL    |                |
+-------------+---------+------+-----+---------+----------------+

相册

+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(11) | NO   | PRI | NULL    | auto_increment |
| name  | text    | NO   |     | NULL    |                |
+-------+---------+------+-----+---------+----------------+

图片

+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| id       | int(11) | NO   | PRI | NULL    | auto_increment |
| name     | text    | NO   |     | NULL    |                |
| alt      | text    | NO   |     | NULL    |                |
| album_id | int(11) | NO   |     | NULL    |                |
| order    | int(11) | NO   |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+

为了简单起见,我不想修改数据库的结构。对我来说最简单的解决方案是:一个产品=>一张专辑=>许多图片

使用连接和别名解决重名错误。

您可以使用 distint 或 group by 让结果按照相同的产品 ID 对齐。

SELECT
*, p.name as nazwa, a.name as nazwa_al, i.name as obrazek
FROM 
products p
JOIN 
albums a on p.album_id = a.id
JOIN
images i ON i.album_id = a.id
GROUP BY p.id
ORDER BY p.order ASC

如果右侧有多行,您需要使用group_concat

SELECT
*, p.name as nazwa, a.name as nazwa_al, group_concat(i.name) as obrazek
FROM 
products p
JOIN 
albums a on p.album_id = a.id
JOIN
images i ON i.album_id = a.id
GROUP BY p.id
ORDER BY p.order ASC