嘿我正在尝试加入2个表,但左侧是映射到所有条目。我正在避免,因为我希望表合并但是NULL值应该是
testtable00:
ownership membership
Johnny Active
testtable01:
pet petname
dog John
cat timmy
parrot Johns
当我像这样加入他们时:
SELECT * FROM (select * from testtable00 inner join testtable01) as u where u.ownership like "%John%";
ownership membership pet petname
Johnny Active dog John
Johnny Active parrot Johns
我想要实现的是
ownership membership pet petname
Johnny Active NULL NULL
NULL NULL dog John
NULL NULL parrot Johns
答案 0 :(得分:3)
由于表之间没有关系,因此您不应该使用JOIN
。您想要的结果看起来像UNION
:
SELECT ownership, membership, NULL AS pet, NULL as petname
FROM testtable00
WHERE ownership like '%John%'
UNION ALL
SELECT NULL AS ownership, NULL AS membership, pet, petname
FROM testtable01
WHERE petname like '%John%'
答案 1 :(得分:0)
如果第一个表中有多个匹配记录,则此查询会为您提供正确的顺序:
SELECT ownership, membership, pet, petname
FROM (
SELECT ownership as x, membership as y, 1 as z,
ownership, membership, null as pet, null as petname
FROM testtable00
UNION ALL
SELECT ownership as x, membership as y, 2 as z,
null, null, pet, petname
FROM testtable00 u inner join testtable01
where u.ownership like "%John%"
) x
ORDER BY x, y, z
演示:http://sqlfiddle.com/#!9/4eb63e/1
| ownership | membership | pet | petname |
|-----------|------------|--------|---------|
| John | Active | (null) | (null) |
| (null) | (null) | dog | John |
| (null) | (null) | cat | timmy |
| (null) | (null) | parrot | Johns |
| Johnny | Active | (null) | (null) |
| (null) | (null) | dog | John |
| (null) | (null) | cat | timmy |
| (null) | (null) | parrot | Johns |