问题描述
我正在尝试从2个表(表A和表B)中获取数据。 表A具有ID,名称,描述。 表B具有名称,详细信息,sub_details。
A中总共有10条记录,B中总共有5条记录。
如果我执行查询,
select a.id,a.name,b.details,b.sub_details
from A a,B b
where a.name = b.name and b.name like "%ABC%";
结果将显示在ABC
列中具有b.name
且在A表中相同的记录。现在,当任何一个表都没有数据时,就会出现问题,在这种情况下,整个结果为空。
我的问题是,即使任何一个表都没有数据,如果我想获得结果,我应该执行哪个查询?
解决方法
使用LEFT JOIN
SELECT a.id,b.name,b.details,b.sub_details
FROM b
LEFT JOIN a ON a.name = b.name
WHERE b.name like '%ABC%'
如果a
中没有匹配的行,则会显示b
和a.id = NULL
中的行。
即使任何表中没有数据,我也要获取结果
您正在描述full join
。不幸的是,MySQL不支持。假设name
是两个表中的唯一键,则可以使用union all
和聚合:
select max(id) as id,name,max(details) as details,max(sub_details) as sub_details
from (
select id,null as details,null as subdetails from a where name like '%ABC%'
union all
select null,details,sub_details from b where name like '%ABC%'
) t
group by name