如何只显示左表中的所有数据一次,并在右表中显示匹配数据

时间:2014-07-20 03:39:11

标签: mysql sql left-join

我想只在左表中显示一次所有数据,并在右表中显示匹配数据。

表1

id        name
1       abc
2       cdr 
3       sdf
4       asew
5       sda
6       few
7       asdq
8       uio
9       kjh

表2

id        table1_id      table2_name
1            1              test1
2            2              test1
3            3              test1
4            4              test1
5            1              test2
6            2              test2
7            3              test2
8            4              test2

我想只显示table1中的所有数据并显示table2中所有匹配的数据,其中table2_name等于' test1'

table1_2

table1_name     table2_name
abc               test1
cdr               test1
sdf               test1
asew              test1
sda               null
few               null
asdq              null
uio               null
kjh               null

3 个答案:

答案 0 :(得分:0)

您可以在SQL中执行此操作,但这不是一个简单的left outer join。关键是减少table2以仅获得每个id的第一次出现。以下使用substring_index() / group_concat()技巧:

select t1.name as table1_name, t2.table2_name
from table1 t1 left outer join
     (select table1_id,
             substring_index(group_concat(table2_name order by id asc), ',', 1) as table2_name
      from table2 t2
      group by table2_name
     ) t2
     on t2.table1_id = t1.id;

答案 1 :(得分:0)

请试试这个......

SELECT  A.name, B.table2_name
FROM    [table 1] A
LEFT JOIN (
SELECT  [table1_id],MAX(table2_name) [table2_name]
FROM    [table 2]) B
ON  A.id = B.[table1_id]

答案 2 :(得分:0)

select t1.name, t2.min_table2_name 
from table1 t1 left join 
(select t2.table1_id, min(t2.table2_name) min_table2_name
    from table2 t2
    group by t2.table1_id
) t2 on t1.id = t2.table1_id

或者如果您只想显示某个table2_name值

select t1.name, t2.min_table2_name 
from table1 t1 left join 
(select t2.table1_id, min(t2.table2_name) min_table2_name
    from table2 t2
    where t2.table2_name = 'test1'
    group by t2.table1_id
) t2 on t1.id = t2.table1_id