具有2个不同ID的SQL SELECT 3表

时间:2017-05-19 13:56:22

标签: mysql sql

我正在尝试进行MySQL查询,该查询合并来自三个表的数据。不幸的是,用于组织数据的ID对于两个表是不同的,但是在第三个表上是相关的。第一个表是这样设置的:

 +---------------------------------------+
 | ID | Meta_Key  | Meta_Value           |
 +---------------------------------------+
 | 1  | name      | John Doe             |                      
 +---------------------------------------+

第二张表是这样设置的:

 +---------------------------------------+
 | ID  | Order_Type      |  Order_ID     |
 +---------------------------------------+
 | 1   | order_type1     |  101          |
 +---------------------------------------+

第3个表是这样设置的:

 +---------------------------------------+
 | Order_ID  | Order_Key  | Order_Value  |
 +---------------------------------------+
 | 101       | order_total| 1000         |
 +---------------------------------------+

我正在寻找一种使用SELECT查询合并这三个表的方法,并将其按ID分组:

 +-----------------------------------------------------------+
 | ID  | Order_ID  | Meta_Value  | Order_Type  | Order_Value |
 +-----------------------------------------------------------+
 | 1   | 101       | John Doe    | order_type1 | 1000        |
 +-----------------------------------------------------------+

4 个答案:

答案 0 :(得分:0)

看起来像连接会做:

select t1.id,
    t2.order_id,
    t1.meta_value,
    t2.order_type,
    t3.order_value
from table1 t1
join table2 t2 on t1.id = t2.id
join table3 t2 on t2.order_id = t3.order_id
where t1.meta_key = 'name';

答案 1 :(得分:0)

您可以根据多个条件加入多个表格:

select
[desired fields]
from tbl_1
     inner join tbl_2 on tbl_1.ID = tbl_2.ID
     inner join tbl_3 on tbl_2.Order_ID = tbl_3.Order_ID

答案 2 :(得分:0)

您可以加入所有三个表并选择所需的字段。

SELECT 
 FirstTable.ID, 
 SecondTable.Order_ID, 
 FirstTable.Meta_Value, 
 SecondTable.Order_Type, 
 ThirdTable.Order_Value
FROM FirstTable 
JOIN SecondTable ON FirstTable.ID = SecondTable.ID 
JOIN ThirdTable ON SecondTable.Order_ID = ThirdTable.Order_ID

答案 3 :(得分:0)

select T1.ID, T2.Order_ID, T1.Meta_Value, T2.Order_Type, T3.Order_Value 
FROM Table_1 T1
LEFT JOIN Table_2 T2 ON T1.ID = T2.ID
LEFT  JOIN Table_3 T3 ON T2.Order_ID= T3.Order_ID

请使用以上查询进行查看