2表查询 - 从每个查询中选择并从两者中进行报告

时间:2016-03-20 15:11:14

标签: mysql

我的平台:Ubuntu 12.04 我在我的数据库中:
- table1:盒子,托盘,...
- table2:托盘,螺栓,......

我已经尝试过这个SQL查询:

select `tray`,bolt from table2 where `tray` in ( select `tray` from table1 where `box` > 11 );

给我一​​个托盘和螺栓列表。

我想:盒子,托盘和螺栓作为输出。怎么样?

提前谢谢。指向额外信用的好教程的指针? : - )

2 个答案:

答案 0 :(得分:1)

您应该使用内部联接而不是IN():

SELECT t.tray,t.bolt,s.box
FROM table2 t 
INNER JOIN table1 s 
 ON(t.tray = s.tray and s.box > 11) 

正如@Reto所提到的,you can read about joins here!

一般情况下:要从多个表中获取数据,您必须使用JOIN,或者在select中使用子查询。

具有子查询(相关查询)的解决方案:

SELECT t.box,t.tray,
       (select s.bolt from table2 s where s.tray = t.tray) as bolt
FROM table1 t 
WHERE t.box > 11) 

答案 1 :(得分:1)

您正在寻找JOIN

select t1.box, tray, t2.bolt
from table1 t1 join
     table2 t2
     using (tray)
where t1.box > 11;
相关问题