Good afternoon, I encountered such a task. You need to display the fields from 3 tables of the database. Suppose a, b, c:

SELECT a.field1, b.field2, c.field3 FROM a, b, c WHERE a.id = 1

If there is a record in the table, then everything is fine, but if there is no record in one of the tables, it does not output anything. So the question is whether it is possible to make such a request, that if in one of the tables there is no suitable record, the output would be null.

a.field1 b.field2 c.field3 1 2 null 2 null 3 

Or is it impossible?

  • What kind of DBMS do you have? - teran
  • @teran MySQL, while the only solution that came to mind is when creating a record in the main table A and generating records in the table b, c with the value null. then it will produce more or less normal, but this does not seem like a good solution. - Roman Neretin
  • Use either a join join or union ell depending on which data and which subt SELECT a.field1, b.field2, c.field3 FROM a left join b on a.key = b.key left join c on a.key = c.key WHERE a.id = 1 - xSx
  • And how are the data related? Do they even have connections? Those. each a.id corresponds to 1 b.id and c.id ? - SLy_huh

1 answer 1

Use JOIN'ы :

 SELECT a.field1, b.field2, c.field3 FROM a LEFT JOIN b ON a.id = b.id LEFT JOIN c ON a.id = c.id WHERE a.id = 1 UNION ALL SELECT a.field1, b.field2, c.field3 FROM a RIGHT JOIN b ON a.id = b.id RIGHT JOIN c ON a.id = c.id WHERE a.id = 1 

Like so