MySQL - 在子查询的别名上使用REGEXP

时间:2014-03-07 18:38:25

标签: mysql regex

如何在子查询的别名上使用REGEXP?

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";




如果我再次选择完整的查询,它会起作用,但我发现这需要花费一些时间

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有效,但该命令不能使用别名

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";




那么在完整查询上选择只做我需要的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用HAVING子句(这不是标准的SQL - MySQL功能):

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";

存在性能影响 - 您的联接是更好的查询。