【问题标题】:SQL how can I skip repeated values on a colum [duplicate]SQL如何跳过列上的重复值[重复]
【发布时间】:2020-12-14 13:30:58
【问题描述】:

因此,根据一些 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 Name Ingredients
1 Rice with chicken Rice
Chicken
2 Rice with eggs and bananas Rice
Eggs
Bananas

【问题讨论】:

  • 今日提示:切换到现代、明确的JOIN 语法。更容易编写(没有错误),更容易阅读和维护,如果需要更容易转换为外连接!
  • 这里的大多数人希望样本表数据和预期结果为格式化文本,而不是图像。
  • @jarlh 哎,谢谢!这是我的 PHP 和 SQL 在线课程的下一步
  • 我会把这一步作为上一步!
  • 请提及您正在使用的 DBMS,即 Oracle、MSSQL 等,同时发布您的预期输出。

标签: php mysql sql database


【解决方案1】:

您需要决定您希望如何在结果中看到ingredients。 一种方法是使用group byp.idp.name 并使用group_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

【讨论】:

  • 知道吗?这是个好主意!
  • 这正是我想要的,非常感谢我的伙伴:D
  • 很高兴为您提供帮助...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 2021-11-24
  • 1970-01-01
  • 2013-10-20
相关资源
最近更新 更多