带有case的MYSQL select语句

时间:2018-04-14 16:21:09

标签: mysql

我尝试进行需要两个表的查询。该查询旨在返回列tReduit或tPlein(在表tarif中)的值,具体取决于列grilleTarif和idUser(表客户端)中的内容。

第一张表:客户端

 nom   prenom     mail          adresse              idUser                            grilleTarif
 admin admin admin@admin.com 10 rue de l'admin m(à"éàé"àé'à_ç-&'à&&=&-&é&à&&&é(è&é_è(§ tPlein

第二张表:tarif

tReduit tPlein nomActivity nPlace 
2        3      NULL       NULL 
7        8      aquaPoney  10

我的查询:

SELECT
    tarif.tReduit, 
    tarif.tPlein, 
    client.grilleTarif, 
    CASE grilleTarif 
        WHEN 'tReduit' 
            THEN tarif.tReduit 
        WHEN 'tPlein' 
            THEN tarif.tPlein
        ELSE tarif.tPlein
        END AS X
FROM tarif, client 
WHERE client.idUser = m(à"éàé"àé'à_ç-&'à&&=&-&é&à&&&é(è&é_èpp§, tarif.nomActivity IS NULL;  

执行时出现语法错误。

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CASE grilleTarif WHEN 'tReduit' then tarif.tReduit when 'tPlein' then tarif.tPle' at line 1.  

Unrecognized keyword. (near "AS" at position 153)
Unexpected token.(near "tarif" at position 156)
Unexpected token. (near "." at position161) 
Unexpected token. (near "tPlein" at position 162)

我试图从How to join row values to column names in a dynamic query

做的另一个查询
SELECT grilleTarif FROM client c
    INNER JOIN 
    ( SELECT tarifCol, tarif from tarif t
        unpivot 
        (
              tarif
              for tarifCol in ([tPlein], [tReduit]) 

        ) unpiv
    ) d
         on c.grilleTarif=t.tarifCol 
where c.idUser = m(à"éàé"àé'à_ç-&'à&&=&-&é&à&&&é(è&é_è(§
and t.nomActivity is NULL;

我仍然有语法错误#1064错误

[...]near 'unpivot (tarif for tarifCol in ([tPlein], [tReduit])) unpiv )
Unexpected character. (near "[" at position 114)
Unexpected character. (near "]" at position 121)
Unexpected character. (near "[" at position 124)
Unexpected character. (near "]" at position 132)

1 个答案:

答案 0 :(得分:0)

OP解决方案。

查询功能:

{{1}}