简体   繁体   中英

MySQL - using REGEXP on an alias of a subquery

How can I use REGEXP on an alias of a subquery?

SELECT 
    colA,
    colB,
    (SELECT colA FROM t2 WHERE t1.colID=t2.colID) as colC
FROM t1
WHERE colC REGEXP '$string'
ORDER BY IF($col = '' OR $col IS NULL,1,0),$col";




It works if I make another select of the complete query, but I see that this costs some time

SELECT * FROM (
    SELECT 
        colA,
        colB,
        (SELECT colA FROM t2 WHERE t1.colID=t2.colID) as colC
    FROM t1
) as temp
WHERE colC REGEXP '$string'
ORDER BY IF($col = '' OR $col IS NULL,1,0),$col";




REGEXP works if I use a join and referencing the table field directly, but the order doesn't work with an alias either

SELECT 
    t1.colA AS colA,
    t1.colB AS colB,
    t2.colA AS colC
FROM t1
LEFT JOIN t2 ON t1.colID=t2.colID
WHERE t2.colA REGEXP '$string'
ORDER BY IF($col = '' OR $col IS NULL,1,0),$col";




So is a select on the complete query the only way to do what I need?

You can use a HAVING clause (this is not standard SQL - MySQL feature):

SELECT 
    colA,
    colB,
    (SELECT colA FROM t2 WHERE t1.colID=t2.colID) as colC
FROM t1
HAVING colC REGEXP '$string'
ORDER BY IF($col = '' OR $col IS NULL,1,0),$col";

There are performance implications - your join is a better query.

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