select query with if函数,可多选

lf5gs5x2  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(209)

我有个问题

SELECT UserName,
       IF(status=1, 'open', status) status,
       IF(status=2, 'closed', status) status,
       c_name
FROM ADMIN a
JOIN admin_course_ ad ON a.adminID=ad.fk_user_id
JOIN admin_courses ac ON ac.c_id=ad.fk_c_id

我的要求是从表中得到status=1,2,3,4,所以不是 1 2 3 4 我想回来 open closed pending defer 如此努力

IF(status=1, 'open', status) status,IF(status=2, 'closed', status) status

但我没有得到预期的价值。任何帮助将不胜感激。

cqoc49vn

cqoc49vn1#

我建议创建一个status types表,其中包含code、name和description列。一旦有了这个条件,就不需要对查询设置任何条件,因为您将通过表之间的内部联接获得名称。

select a.UserName, ..., s.name
from admin a 
inner join statuses s on s.statusCode = a.status
join admin_course_ -- rest of your joins and query
...

您还可以使用mysql的case子句实现所需的功能(请看这个代码示例取自mysql文档)https://www.w3schools.com/sql/func_mysql_case.asp):

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN "The quantity is greater than 30"
    WHEN Quantity = 30 THEN "The quantity is 30"
    ELSE "The quantity is something else"
END
FROM OrderDetails;

希望这有帮助

cclgggtu

cclgggtu2#

您可以使用case语句。例如:

SELECT c_name,
       UserName,
       (CASE status
            WHEN 1 THEN 'open'
            WHEN 2 THEN 'closed'
            WHEN 3 THEN 'pending'
            WHEN 4 THEN 'defer'
            ELSE "undefined"
        END) AS status_title
FROM admin a
JOIN admin_course_ ad ON a.adminID=ad.fk_user_id
JOIN admin_courses ac ON ac.c_id=ad.fk_c_id

相关问题