mysql在同一查询中使用所选变量

时间:2013-08-26 12:59:37

标签: mysql

我有一个表'booking_summary',它存储方法的类型(method = Air或Sea)。 我必须根据方法列将此表与其他两个表中的一个连接起来。

如果方法是Air,那么加入的表是booking_air,如果是sea,那么它就是booking_sea。 我不想在这个特定的页面上运行多个查询。

这是我最近的尝试,显然已经失败。带有别名的table_name是我想要在同一个查询中的表。

$sql = "select case when a.shipping_method = 'Sea' then 'booking_sea' else 'booking_air' end 'table_name',
                case when a.user_id ='$active_id' then 'y' else 'no' end 'generate_access',
                case when c.mbl is NULL then 'Pending' else c.mbl end 'mbl_status',
                case when c.hbl is NULL then 'Pending' else c.hbl end 'hbl_status',
                a.*,b.user_name 
                from booking_summary a
                left join registered_users b 
                on a.user_id = b.user_id
                left join table_name c
                on a.id = c.id
                where (a.user_id = '$active_id' or a.forwarder='$active_id')";

任何建议都会非常有帮助。感谢

2 个答案:

答案 0 :(得分:1)

我不确定这是否会起作用,但无论如何......

$sql = "select case 
                when a.user_id ='$active_id' then 'y' 
                else 'no' end 'generate_access',
            if(a.shipping_method = 'Sea',
                case when c.mbl is NULL then 'Pending' else c.mbl end,
                case when d.mbl is NULL then 'Pending' else d.mbl end ) 'mbl_status',
            if(a.shipping_method = 'Sea',
                case when c.hbl is NULL then 'Pending' else c.hbl end,
                case when d.hbl is NULL then 'Pending' else d.hbl end ) 'hbl_status',
                 a.*,b.user_name 
                from booking_summary a
                left join registered_users b  on a.user_id = b.user_id
                left join booking_sea c  on a.id = c.id
                left join bookin_air d on a.id=d.id
                where (a.user_id = '$active_id' or a.forwarder='$active_id')";

答案 1 :(得分:0)

如果不完全理解你的结构,我可以想到这个解决方案

SELECT a.shipping_method 
FROM   shipping_summary AS A 
       LEFT JOIN (SELECT *, 
                          'AIR' AS METHOD 
                   FROM   shipping_air) AS B 
               ON A.shipping_method = B.method 
       LEFT JOIN (SELECT *, 
                          'SEA' AS METHOD 
                   FROM   shipping_sea) AS C 
               ON A.shipping_method = C.method 

这是一个高级答案,因为我没有要选择的字段以及更多优化查询的方法。