首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > Mysql >

mysql多表查询有关问题

2012-05-29 
求助mysql多表查询问题我有一张表A 主键id(自增)令外有表B、C、D 他们的第一列都是A的主键ID的值(A的主键ID

求助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 tableNamefrom aleft join b on a.id=b.aidleft join c on a.id=c.aidleft join d on a.id=d.aidorder 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.tfrom A left join (select 'B' as t,id from Bunion allselect 'C' as t,id from Bunion allselect '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 didfrom Alimit 10
[解决办法]
探讨

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

热点排行