Sql查询获取两个表的连接,并且两个表都有查询位置

时间:2017-03-23 13:18:29

标签: sql join left-join

坚持加入,尝试左,右,左外,右外连接

表1

selectionID    name     type
1              abc       1
2              def       1
3              ghi       2
4              dhi       2
5              gki       2
6              ppp       2

表2

TID    UserID    selectionID   isOK
1       10       3              0
2       19       3              0
3       10       8              0
6       10       5              1

期望的结果是 加入 从表1中选择type = 2 从表2中选择UserID = 10

selectionID    name     type    TID             userID 

3              ghi       2       1              10
4              dhi       2       undefined      undefined/null
5              gki       2       undefined      undefined/null
6              ppp       2       6              10

所以基本上我希望表1中的所有数据都适合where子句及其在表2中的相应数据与另一个where子句

只要我做了研究,我就需要使用第二张表的内部查询...我是否正确行事?

4 个答案:

答案 0 :(得分:2)

尝试以下查询:

SELECT t1.selectionID, t1.name, t1.type, t2.tid, t2.userID
FROM table1 t1 LEFT JOIN table2 t2 ON t1.type = t2.TID AND t2.userID = 10
WHERE t1.type = 2;

答案 1 :(得分:2)

坚持加入,尝试左,右,左外,右外连接 ......好LEFT JOINLEFT OUTER JOIN相同。顺便说一句,你正在寻找LEFT JOIN可能像

select t1.selectionID,
    t1.name,
 t1.type,
 t2.TID,
 t2.UserId
from table1 t1 
left join table2 t2 on t1.selectionID = t2.selectionID
and t2.UserId = 10
where t1.type = 2;

答案 2 :(得分:0)

您可能失败了,因为将条件放在where子句中。如果某行没有加入,则其列中会有null个,因此where条件会丢弃这些行

select  *
from    table1 t1
left join
        table2 t2
on      t1.selectionID = t2.selectionID and
        t2.userID = 10
where   t1.type = 2

另一种方法是使用coalesce

强制接受空行
select  *
from    table1 t1
left join
        table2 t2
on      t1.selectionID = t2.selectionID and
where   t1.type = 2 and
        coalesce(t2.userID, 10) = 10

答案 3 :(得分:0)

select * from table1 t1
left join table2 t2 ON t1.SelectionID = t2.SelectionID
where t1.type = 2 AND t2.UserID = 10