MYSQL使用SUB SELECT到WHERE CLAUSE

时间:2017-10-03 12:01:39

标签: php mysql subquery

我想问一下是否有可能在where子句中调用我的子选择,例如HELPER1将用作WHERE HELPER1 LIKE 'SAMPLE%'

这是我的示例查询

SELECT dispatch_id, FROM_UNIXTIME(expected_departure_date, '%Y-%m%-%d %h:%i:%s') as dt,
FROM_UNIXTIME(expected_wh_arrival, '%Y-%m%-%d %h:%i:%s') as at, truck, FROM_UNIXTIME(created_on, '%Y-%m%-%d %h:%i:%s') as created,remarks, agent_id,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=helper1_id) as hp1,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=helper2_id) as hp2,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=helper3_id) as hp3,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=helper4_id) as hp4,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=helper5_id) as hp5,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=driver) as driver1,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=driver2) as driver2,
(SELECT fullname FROM dev.tpl_user_profiles WHERE uid=dispatcher_uid) as dispatcher,
(SELECT td.destination FROM dev.tpl_destination as td WHERE td.id=tdd.destination ) as dest,
(SELECT delivery_type FROM dev.tpl_delivery_type WHERE id=delivery_type ) as det,
 (SELECT plate_number FROM dev.tpl_trucks  WHERE id=truck ) as pn ,
 status
from dev.tpl_dispatch as tdd WHERE
EXISTS (SELECT td.destination FROM dev.tpl_destination as td WHERE td.destination LIKE 'Ac%')

1 个答案:

答案 0 :(得分:0)

没有。 SQL不允许在WHERE中为定义它的SELECT使用列别名。

我可以想到三个选择:

  1. 使用子查询。但这会产生实现子查询的开销(在MySQL中,而不是在其他数据库中)。
  2. 重新排列查询以使用LEFT JOIN而不是子查询。但这是很多工作。
  3. 使用MySQL扩展程序HAVING
  4. 在非聚合查询中,MySQL允许您使用引用列别名的HAVING子句。所以你可以添加:

    HAVING HELPER1 LIKE 'SAMPLE%'