左连接查询与同一列显示重复记录

时间:2016-04-15 11:53:56

标签: sql sql-server

我有三个名为

的表
  

tbl_1st
  tbl_2nd
  tbl_3rd

每次记录都以列名tt作为主键输入第一个表。其他两个表用作外键,(但其他两个表的tt2包含主键)

这三个表的数据是:

第一张表

enter image description here

第二张表

enter image description here

第三表

enter image description here

运行此查询时

<?php
$siteLinkDesc = array_reverse($siteLinkDesc);
?>

它显示了重复记录,我想要的是,如果特定tt第2和第3个表匹配tt2它将它合并在一行中,并且保持显示null或其他。

假设在这种情况下我只需要显示2个reocrds,但如果我改变了条件

  

其中tbl_1st.tt = 100000000000000002

它只显示3条记录,怎么会发生?任何想法

修改

的DataTypes tt是数字(20,0) tt2是数字(22,0) DateTime是datetime 状态是位

输出: enter image description here

预期输出 enter image description here

案例2输出: enter image description here

但在这种情况下预计会有3行。

2 个答案:

答案 0 :(得分:1)

试试这个

select * from tbl_1st
left join tbl_2nd on tbl_1st.tt = tbl_2nd.Tt
left join tbl_3rd on tbl_1st.tt = tbl_3rd.tt AND tbl_2nd.Tt = tbl_3rd.tt 
where tbl_1st.tt = 100000000000000001

答案 1 :(得分:0)

听起来你应该加入tbl_2ndtbl_3rd,如下所示:

select * from tbl_1st
left join tbl_2nd on tbl_1st.tt = tbl_2nd.Tt
left join tbl_3rd on tbl_2nd.TT2 = tbl_3rd.tt2 -- <-- Notice the change in alias
where tbl_1st.tt = 100000000000000001