子查询
的子查询使用MySQL专栏中,我有两个表子查询
报告
id consultants
1 1,2,3,4
用户
id name
1 John
2 Tom
当我尝试运行此查询我得到一个错误:“未知列' reports.consultants'in'where clause'“
SELECT reports.id,
(SELECT GROUP_CONCAT(name SEPARATOR ", ") from (SELECT name from users where users.id in (reports.consultants)) a) as consultant
FROM reports
我想过使用一个单独的ReportConsultants表,但我认为在报表中存储顾问可能会使查询更有效率,并想知道是否有办法做到这一点。在代码中使用这种结构也更简单。
是的,它是可能的,语法需要略有不同
SELECT reports.id,
(SELECT GROUP_CONCAT(name SEPARATOR ", ") from users where FIND_IN_SET(users.id, reports.consultants)) as consultant
FROM reports
修复你的数据结构!您不应该将字符串列表存储在一个字符串中。这里有一些原因:
- 数字应该存储为数字,而不是字符串。
- ID应该声明外键约束。
- SQL的强项不是字符串函数。
以表示数据正确的方法是用结合表,
create table ReportConsultants (
ReportConsultantId int auto_increment primary key,
ReportId int,
ConsultantId,
constraint fk_reportconsults_report foreign key (reportid) references reports(reportid),
constraint fk_reportconsults_consultant foreign key (consultantid) references consultants(consultantid)
);
第一列(可能)是冗余的,但如果使用自动增量ID,则必须将其定义为PRIMARY KEY的(的一个组成部分)。 – Strawberry
是的,这绝对是一种方式。我认为我的方式可能会使查询更快。有没有办法让子查询使用该字段? – ykay
@ykay相应地修改你的问题。 – Strawberry
参见正常化。或者不要打扰RDBMS – Strawberry
首先这是非常糟糕的设计。 –
@Strawberry你如何推荐设计? – ykay