在MySQL中使用LEFT JOIN组合两个表

时间:2012-06-19 12:44:47

标签: mysql

我有两张桌子

表1

+-------+-------+
| NAME  | PRICE |
+-------+-------+
| ITEM1 |  100  |
+-------+-------+
| ITEM2 |  200  |
+-------+-------+
| ITEM3 |  300  |
+-------+-------+

table2 重复ITEM1和ITEM2

    +-------+--------+---------+
    | NAME  | SUFFIX | CODE    |
    +-------+--------+---------+
    | ITEM1 | 1      | ITEM1_1 |
    +-------+--------+---------+
    | ITEM1 | 2      | ITEM1_2 |
    +-------+--------+---------+
    | ITEM2 | 1      | ITEM2_1 |
    +-------+--------+---------+

我如何通过mySQL做到这个结果?

+-------+-------+----------+
| NAME  | PRICE |   NAME2  |
+-------+-------+----------+
| ITEM1 |  100  |  ITEM1   |
+-------+-------+----------+
| ITEM2 |  200  |  ITEM2   |
+-------+-------+----------+
| ITEM3 |  300  |  NULL    |
+-------+-------+----------+

我想从table1中获取不是的table1中的元素。在这种情况下,我想要的元素是ITEM3。我可以用LEFT JOIN做到这一点吗?

2 个答案:

答案 0 :(得分:1)

select * from table1 t1
left outer join table2 t2 on t1.name = t2.name
where t2.name is null

答案 1 :(得分:1)

Select * from table1 s Left join table2 as t on s.NAME=t.NAME where t.NAME IS NULL