读书人

mysql多表查询有关问题

发布时间: 2012-05-29 12:16:00 作者: rapoo

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

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

非常感谢。


[解决办法]

SQL code
declare @str varchar(10)set @str=''if exists (select 1 from B where id in(select top 10 id from A))beginset @str='tbl_A'if exists (select 1 from C where id in(select top 10 id from A))BEGIN   set @str=@str+'tbl_B'  if exists (select 1 from D where id in(select top 10 id from A))  begin  set @str=@str+'tbl_D'  endENDprint '匹配到的表为:'+@strend--try
[解决办法]
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 Server

热点推荐