1

I have two tables

Reports

id     consultants
1      1,2,3,4

Users

id    name
1     John
2     Tom

When I try to run this query I get an error: "Unknown column '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

I've thought of using a separate ReportConsultants table but I thought storing the consultants in the reports table may make the query more efficient and wondering if there is a way to do this. Using this kind of structure is also much simpler in the code.

4
  • 1
    See normalisation. Or don't bother with an RDBMS Commented Sep 14, 2017 at 10:37
  • First of all this is very bad design. Commented Sep 14, 2017 at 10:37
  • @Strawberry how do you recommend to design? Commented Sep 14, 2017 at 10:39
  • @AnkitBajpai how do you recommend to design? Commented Sep 14, 2017 at 10:39

2 Answers 2

1

Yes it is possible, the syntax needs to be slightly different

SELECT reports.id,
  (SELECT GROUP_CONCAT(name SEPARATOR ", ") from users where FIND_IN_SET(users.id, reports.consultants)) as consultant
FROM reports
Sign up to request clarification or add additional context in comments.

Comments

0

Fix your data structure! You should not be storing lists of ids in a string. Here are some reasons:

  • Numbers should be stored as numbers, not strings.
  • Ids should have declared foreign key constraints.
  • SQL's strength is not string functions.

The right way to represent the data is with a junction table,

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)
);

5 Comments

The first column is (probably) redundant, but if an autoincrementing id is used, then it must be defined as (a component of) a PRIMARY KEY.
Yeah, it's definitely a way to go. I thought my way might make the query faster. Is there a way to get the subquery to use the field?
@ykay Amend your question accordingly.
@ykay Obviously, I mean once you've fixed your broken structure.
@ykay . . . Ask another question, once you have fixed the data structure. Don't make significant revisions to a question after it has answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.