我有一个查询
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
但是我没有得到期望值。任何帮助将不胜感激。
答案 0 :(得分:2)
您可以使用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
答案 1 :(得分:0)
我建议使用代码,名称和描述列创建一个状态类型表。一旦有了这个,您就不需要查询任何条件,因为您将通过表之间的内部联接获得名称。
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;
希望这会有所帮助