php - 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 | 米饭配鸡蛋和香蕉 | 米 |
蛋 | ||
香蕉 |
解决方案
您需要决定您希望ingredients
在结果中看到的方式。一种方法是使用group by
withp.id
或p.name
andgroup_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
推荐阅读
- metal - 正确的是将数组从 Metal Kernel 函数传递给本地函数
- java - android - 如何从另一个布局声明一个小部件?
- android-studio - 应用程序退出时出现未处理的异常
包含 - java - Firebase android 可以在模拟器上运行,但不能在设备上运行
- aws-lambda - 使用 Amazon 登录以获得 Alexa Skills (LWA)
- sql - 如何在 SQL 中对一组元素进行大小写
- c# - 控制台应用程序中的 SingalR
- angular - 在没有 AOT 的情况下启用生产模式:Angular 4
- python - python /瓶文件名和重复
- javascript - 我不确定为什么我在使用 react redux 时看到 undefined