简体   繁体   English

在MySQL中选择查询多个表

[英]Select Query in MySQL for multiple tables

I m working in MySQL and have to write a select query. 我在MySQL中工作,必须编写一个select查询。

I have related data in four tables. 我在四个表中有相关​​数据。 Now, the parent table may have data whose child data may not be present in lower tables. 现在,父表可能包含其子数据可能不在较低表中的数据。

I want to write a single query to get data from all four tables, irrespective of situation that data is present in child tables or not . 我想编写一个查询来从所有四个表中获取数据,而不管子表中是否存在数据的情况

I have tried to write nested select and joins as below, but m not getting the data. 我试图写嵌套的选择和联接如下,但我没有得到数据。

select * from property p where p.Re_ID in 
  (select Re_id from entry e where e.Re_ID in
    (select Re_id from category c where c.Re_ID in
      (select id from re)))

Please help me how to get data from all 4 tables. 请帮助我如何从所有4个表中获取数据。

If cir_registry is the master, you can select from that and LEFT JOIN the other tables in the order they're distant from cir_registry ; 如果cir_registry是主人,你可以从选择和LEFT JOIN在他们从遥远的顺序其他表cir_registry ;

SELECT r.ID rId, r.Description rDescription, c.ID cId ...
       ...
       p.Data_Type pDataType 
FROM cir_registry r
LEFT JOIN cir_category c ON c.Registry_ID = r.ID
LEFT JOIN cir_entry    e ON e.Category_ID = c.ID
LEFT JOIN cir_property p ON p.Entry_IDInSource = e.IDInSource

You should also alias the columns as above, otherwise, for example, p.ID and c.ID will both show up in the result set as ID , and you'll only be able to access one of them. 您还应该为上述列加别名,否则,例如, p.IDc.ID都将显示为结果ID ,并且您将只能访问其中之一。

You might need UNION? 您可能需要UNION吗? Something like: 就像是:

Select * FROM cir_registry
Union
Select * FROM cir_entry
Union
Select * FROM cir_property

Check the official doc here: http://dev.mysql.com/doc/refman/5.0/en/union.html 在此处检查官方文档: http : //dev.mysql.com/doc/refman/5.0/en/union.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM