如何从两个表中获取数据?

时间:2015-07-07 15:49:50

标签: sql

我有两张桌子Table1& Table2

表1

s.no|uniqueNumber | assigned_to
1.  | S123        | Tom
2.  | S234        | Harry
3.  | S345        | Tom

表2

s.no|uniqueNumber | status
1.  | S123        | approve
2.  | S234        | approve
3.  | S345        | reject

我想抓取uniqueNumberstatus& {}的approve assignedTom。我正在尝试将UNIONwhere子句一起使用。但我认为UNION在这里不起作用。怎么做到这一点?

3 个答案:

答案 0 :(得分:1)

您必须使用加入:

select table1.uniqueNumber, status, assigned_to
from table1
inner join table2 on table1.uniqueNumber = table2.uniqueNumber
where status = 'approve' and assigned_to ='Tom'

答案 1 :(得分:1)

这样的东西
SELECT    t1.uniquenumber
FROM      table1 AS t1
JOIN      table2 AS t2
ON        t1.uniquenumber = t2.uniquenumber
WHERE     t2.status = 'approve'
AND       t1.assigned_to = 'Tom'

答案 2 :(得分:0)

您可以使用子查询,如...

select table1.uniqueNumber from table1 where assigned_to='Tom' 
       and table1.uniqueNumber 
       in  (
             select table2.uniqueNumber from  table2 where 
             status='approve'          
            );

OR ..

你可以直接加入两个表..

select table1.uniqueNumber
       from table1 join table2 
         on table1.uniqueNumber = table2.uniqueNumber
         where status = 'approve' and assigned_to ='Tom'