SQL / MySQL:在连接查询中只获得一些不同的列

时间:2016-03-16 12:46:40

标签: php mysql sql

在我的MySQL数据库中,我有以下表格:

食谱(= ricette),其中包含食谱的ID和一些基本信息

成分(= ingredienti)在那个食谱中有尽可能多的成分,最后是表

recipe_kind (= tiporicetta),其中包含食谱的ID和食谱的种类。

我想得到配方的所有成分,所以我执行:

SELECT DISTINCT
    r.nome,
    r.descrizione,
    r.persone,
    t.tipo,
    c.cibo,
    i.quantita,
    i.unitamisura_id
FROM
    ricette AS r
        LEFT JOIN
    ingredienti AS i ON i.ricette_id = r.id
        LEFT JOIN
    cibo AS c ON c.id = i.cibo_id
        LEFT JOIN
    tiporicetta AS t ON t.id = r.tiporicetta_id
WHERE
    (r.id = '52')

但是通过该查询,我可以多次获得名称,描述,人物和种类,每行一次。相反,我想只有一次nome,descrizione,persone和tipo,然后是成分列表。 如何使用唯一查询来完成此操作?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    r.nome,
    r.descrizione,
    r.persone,
    "", "", "", ""
FROM ricette AS r
WHERE 
    (r.id = '52')

UNION

SELECT
    "", "", ""
    t.tipo,
    c.cibo,
    i.quantita,
    i.unitamisura_id
FROM
    ricette AS r LEFT JOIN
    ingredienti AS i ON i.ricette_id = r.id LEFT JOIN
    cibo AS c ON c.id = i.cibo_id LEFT JOIN
    tiporicetta AS t ON t.id = r.tiporicetta_id
WHERE
    (r.id = '52')