MySQL声明中的条件联盟

时间:2014-04-24 21:07:57

标签: mysql if-statement union

在以下声明中:

SELECT placeId, name, ico, lv, url
FROM
(
    SELECT placeId, urlRef, name, ico, lv
    FROM
    (
        SELECT placeId, urlRef, name, ico, levenshtein_ratio( :place, name ) AS lv
        FROM places
        WHERE name SOUNDS LIKE :place AND dm( name ) = dm( :place )
        HAVING lv > 59
        UNION
        SELECT placeId, urlRef, placeNameVariants.name AS name, ico, levenshtein_ratio( :place, placeNameVariants.name ) AS lv
        FROM placeNameVariants
        LEFT JOIN places ON placeRef = placeId
        WHERE placeNameVariants.name SOUNDS LIKE :place AND dm( placeNameVariants.name ) = dm( :place )
        HAVING lv > 59
        UNION
        SELECT placeId, urlRef, name, ico, 0 AS lv
        FROM places
        WHERE name REGEXP :placeLike
    ) AS subA
    ORDER BY lv DESC
) As subB
LEFT JOIN urls ON urlRef = urlId
GROUP BY placeId

我只想在第三个UNION(第20行)之后运行SELECT,当一个字符串超过3个字符时,例如

IF( CHAR_LENGTH( :placeLike ) > 3 ) THEN
UNION
SELECT placeId, urlRef, name, ico, 0 AS lv
FROM places
WHERE name REGEXP :placeLike

但是我找不到任何办法。有办法吗?或者这里的最佳做法。目前我发送'^ $'到REGEXP时:placeLike是3 ro less chars,这似乎不是一个很好的解决方案。

2 个答案:

答案 0 :(得分:3)

你试过这个吗?

UNION
SELECT placeId, urlRef, name, ico, 0 AS lv
FROM places
WHERE LENGTH(:placeLike) > 3 AND name REGEXP :placeLike 

答案 1 :(得分:1)

这就是你想要的最后一个联盟吗?

    ...
    UNION
    SELECT placeId, urlRef, name, ico, 0 AS lv
    FROM places
    WHERE length(name) > 3
    ...

但我不确定我是否理解应该是什么“地方”。它是变量吗?它是标准的正则表达式吗?我不明白。我知道它是一个绑定变量,但我不知道它应该是什么。