首页 > 解决方案 > SQL如何跳过列上的重复值

问题描述

因此,按照一些 stackoverflow 社区给我的提示,我创建了这个“数据库”来保存我的菜肴及其成分。我唯一的问题是我不希望看到不必要的重复名称和 ID,我想知道是否有任何方法可以避免它。这是一个屏幕截图,代码如下。谢谢

这是屏幕截图。

CREATE TABLE platos ( 
    id int auto_increment not null primary key, 
    name varchar(255) not null
)ENGINE=InnoDb;

CREATE TABLE ingredientes_para_platos (
    id  int auto_increment primary key,
    plato_id int not null,
    ingredientes varchar(255) not null,
    CONSTRAINT fk_ingredientes_para_platos FOREIGN KEY(plato_id) REFERENCES platos(id)
)ENGINE=InnoDb;

SELECT p.id,p.name,i.ingredientes
    FROM platos p, ingredientes_para_platos i
        WHERE p.id = i.plato_id; 

询问的额外数据:我正在使用 MySQL,预期的输出就像

ID 姓名 原料
1 糯米炖鸡
2 米饭配鸡蛋和香蕉
香蕉

标签: phpmysqlsqldatabase

解决方案


您需要决定您希望ingredients在结果中看到的方式。一种方法是使用group bywithp.idp.nameandgroup_concat将成分合并到一列中。见https://www.mysqltutorial.org/mysql-group_concat/

SELECT p.id,p.name, GROUP_CONCAT(i.ingredientes)
    FROM platos p, ingredientes_para_platos i
        WHERE p.id = i.plato_id GROUP BY p.id;

然后你会看到:

2 | Rice with bananas and eggs | Rice, Bananas, Eggs
1 | Rice with chicken          | Rice, Chicken

推荐阅读