mysql在同一查询中使用所选变量
我有一个“booking_summary”表,其中存储了方法的类型(方法=空运或海运)。 根据method列,我必须将这个表与另外两个表中的一个连接起来 如果方法是Air,那么要加入的表是booking\u Air,如果是sea,那么它是booking\u sea。 我不想在此特定页面上运行多个查询 这是我最近的一次尝试,显然失败了。带别名的表\u名称就是我希望在同一查询中使用的表mysql在同一查询中使用所选变量,mysql,Mysql,我有一个“booking_summary”表,其中存储了方法的类型(方法=空运或海运)。 根据method列,我必须将这个表与另外两个表中的一个连接起来 如果方法是Air,那么要加入的表是booking\u Air,如果是sea,那么它是booking\u sea。 我不想在此特定页面上运行多个查询 这是我最近的一次尝试,显然失败了。带别名的表\u名称就是我希望在同一查询中使用的表 $sql = "select case when a.shipping_method = 'Sea' then '
$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')";
任何建议都会很有帮助。谢谢嗯,我不确定这是否有效,但无论如何
$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')";
如果不完全理解您的结构,我可以想到这个解决方案
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
这是一个高层次的答案,因为我没有要选择的字段和更多优化查询的方法。您可以创建一个带有表结构的sqlfiddle示例吗?在不知道实际的fieldstable-1-id的情况下编写联接查询是很困难的,类型(type=sea或air)table_air和table_sea是另外两个表。现在我查询表1以首先获取类型。现在根据类型,我必须加入table_sea或table_air。这是我似乎无法应用的逻辑。你能在那里创建一个例子吗?我想看看表海和表空的结构,看看是否有机会加入其中。这非常有效。非常感谢@skv-谢谢你的帮助。@user1411837很高兴它起作用了,但是你是说我的建议也起作用了吗?@user1411837请注意,你实际上是在进行连接,然后才选择专栏。它以从引擎中提取更多数据为代价,为您节省了一个查询。这是一个问题,如果你对带宽计费。