如何在mysql的where子句中使用别名?
SELECT
*,
CASE roles.rol_active
WHEN '1' THEN 'yes'
WHEN '0' THEN 'no'
END AS roles_active
FROM
roles
WHERE
rol_is_deleted =
AND (rol_name LIKE '%ac%'
OR rol_display_name LIKE '%ac%'
OR rol_description LIKE '%ac%'
OR rol_active LIKE '%ac%'
OR rol_updated_by LIKE '%ac%'
OR rol_updated_at LIKE '%ac%')
ORDER BY rol_name asc
LIMIT 10 OFFSET 0;
答案 0 :(得分:2)
实际上你不能,因为select
子句在where
子句之后被评估(此时没有别名)。但是,您可以使用having
子句或使用临时表。
答案 1 :(得分:2)
将当前查询的一部分包含在派生表中:
select * from
(
SELECT
*,
CASE roles.rol_active
WHEN '1' THEN 'yes'
WHEN '0' THEN 'no'
END AS roles_active
FROM
roles
) as dt
WHERE
rol_is_deleted =
AND (rol_name LIKE '%ac%'
OR rol_display_name LIKE '%ac%'
OR rol_description LIKE '%ac%'
OR rol_active LIKE '%ac%'
OR rol_updated_by LIKE '%ac%'
OR rol_updated_at LIKE '%ac%')
ORDER BY rol_name asc
LIMIT 10 OFFSET 0;
您甚至可以有两个单独的WHERE
条款。一个用于子查询中的列条件,另一个用于外部查询中的列别名条件。即类似的东西:
...
WHERE column-conditions
) as dt
WHERE column-alias-conditions
...