简体   繁体   中英

MYSQL USING SUB SELECT TO WHERE CLAUSE

HI I would like to ask if possible to call my sub select in where clause like example the HELPER1 would be use as WHERE HELPER1 LIKE 'SAMPLE%'

Here's my sample query

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%')

No. SQL does not allow the use of a column alias in the WHERE for the SELECT where it is defined.

I can think of three options:

  1. Use a subquery. But this imposes overhead for materializing the subquery (in MySQL, not other databases).
  2. Rearrange the query to use LEFT JOIN rather than subqueries. But that is a lot of work.
  3. Use the MySQL extension to HAVING .

In a non-aggregation query, MySQL allows you to use a HAVING clause that refers to the column aliases. So you can add:

HAVING HELPER1 LIKE 'SAMPLE%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM