SQL从第一个表返回行,然后分别连接表

时间:2015-09-27 11:45:03

标签: mysql sql

我有两张桌子。我想选择表1中的所有行,以及表2中共享相同ID的所有行。我需要从表1返回行,然后,如果它们存在,则分别返回表1和2的连接行。如果表2中没有匹配,则下面的当前代码返回表1中的行。但是,如果表2中存在匹配,则只返回连接的行。

SELECT
    table1.id,
    COALESCE(table2.name, table1.name) AS name
FROM
    table1
LEFT JOIN
    table2
ON
    table1.id = table2.id
WHERE
    table1.stock = 0

这就是我追求的目标:

**Table 1**
id  | name  | stock
101 | sock  | 4
102 | hat   | 0
103 | belt  | 0

**Table 2**
id  | name
101 | banana
102 | pear
102 | apple

**Query output**
id  | name
102 | hat
102 | pear
102 | apple
103 | belt

1 个答案:

答案 0 :(得分:0)

从你的输出中,我收集到你想要的东西,比如两个表中的所有行,其中表1中的id的库存为0.

select id, name
from table1
where stock = 0
union all
select id, name
from table2 t2
where exists (select 1 from table1 t1 where t1.id = t2.id and t1.stock = 0);
相关问题