日期:2014-05-17  浏览次数:20570 次

联合查询定位问题
本帖最后由 XingGuangYingYing 于 2013-03-12 02:51:55 编辑
比如2个表

定位表:
ID TRID  PID
99   2     3

价格表:
ID  P1  P2  P3
1   20   25  31
2   13   15  19

定位表里面,ID为99的行,TRID为2, PID为3, 我要查询的是价格表里面ID为2 列名为P3的值 即19

请问,SQL要怎么写? 





------解决方案--------------------
select a.p3 from 价格表 a join 定位表 b on a.id=b.trid where b.id=99

------解决方案--------------------
select (case when t1.pid = 1 then t2.p1 when t1.pid = 2 then t2.p2 when t1.pid = 3 then t2.p3 end) as p from tablepos t1 join tableprice t2 on t1.trid = t2.id;
------解决方案--------------------
mysql> select (case when t1.pid = 1 then t2.p1 when t1.pid = 2 then t2.p2 when t
1.pid = 3 then t2.p3 end) as p from tablepos t1 join tableprice t2 on t1.trid =
t2.id;
+------+

------解决方案--------------------
 p    
------解决方案--------------------

+------+

------解决方案--------------------
   19 
------解决方案--------------------

+------+
1 row in set (0.00 sec)
------解决方案--------------------
如果只有p1p2p3用2楼方法吧,不定个数需要动态

declare @sql varchar(max)
select @sql = 'select P' + cast(PID as varchar) + ' from 价格表 where id = ' + cast(TRID as varchar)
from 定位表
where ID = 99

exec(@sql)