日期:2014-05-16  浏览次数:20831 次

求助mysql多表查询问题
我有一张表A 主键id(自增)
令外有表B、C、D 他们的第一列都是A的主键ID的值(A的主键ID只可能在B、C、D的一个中出现)

我现在想实现这样的功能找出A的前10条记录和匹配到的表明。

非常感谢。

------解决方案--------------------
SQL code
select a.*,if(b.aid is not null,'B',if(c.aid is not null,'C','D')) as tableName
from a
left join b on a.id=b.aid
left join c on a.id=c.aid
left join d on a.id=d.aid
order by a.id 
limit 10;

------解决方案--------------------
探讨

SQL code
select a.*,if(b.aid is not null,'B',if(c.aid is not null,'C','D')) as tableName
from a
left join b on a.id=b.aid
left join c on a.id=c.aid
left join d on a.id=d.aid
order by a.id
limit 10;……

------解决方案--------------------
SQL code
select a.id,u.t
from A left join (
select 'B' as t,id from B
union all
select 'C' as t,id from B
union all
select 'D' as t,id from B
) u on a.id=u.id

------解决方案--------------------
探讨

SQL code
select a.id,u.t
from A left join (
select 'B' as t,id from B
union all
select 'C' as t,id from B
union all
select 'D' as t,id from B
) u on a.id=u.id

------解决方案--------------------
贴建表及插入记录的SQL,及要求结果出来看看


select a1.id,b1.bz from A a1 left join (
select 'B' as bm,id from b
union all
select 'C' as bm,id from c
union all
select 'D' as bm,id from d
) b1 on a1.id=b1.id order by a1.id desc limit 10

or

select a1.id,b1.bz from A a1 left join (
select 'B' as bm,id from b
union all
select 'C' as bm,id from c
union all
select 'D' as bm,id from d
) b1 on a1.id=b1.id where b1.id is not null order by a1.id desc limit 10
------解决方案--------------------
select a.id,u.t
from A left join (
select 'B' as t,id from B
union all
select 'C' as t,id from B
union all
select 'D' as t,id from B
) u on a.id=u.id order by a1.id desc limit 10


------解决方案--------------------
SQL code
select a.id, (select id from b) as bid,
    (select id from c) as cid,
    (select id from d) as did
from A
limit 10

------解决方案--------------------
探讨

如果B C D 每张表都有10万级别的数据,我发现效率很差啊。有没有效率比较高的,感谢各位大虾。