[英]How can I use an alias for a CONCAT in MySQL?
I need to return an alias column eventTitle
of which the content can be variable depending on whether another column's value is null
.我需要返回一个别
eventTitle
,其内容可以是可变的,具体取决于另一列的值是否为null
。 I also need to use the value of that alias to concatenate some other values to return another alias title
.我还需要使用该别名的值来连接其他一些值以返回另一个别名
title
。
I am running the following query:我正在运行以下查询:
$sql = 'SELECT
CASE WHEN session.title IS NOT NULL
THEN session.title
ELSE course.title
END AS eventTitle,
CONCAT(eventTitle, "\n", session.city, ", ", session.state) AS title,
FROM session
LEFT JOIN course ON course.id = session.course_id';
I get the following error:我收到以下错误:
Unknown column 'eventTitle' in 'field list'
“字段列表”中的未知列“eventTitle”
You can't refer to column aliases in the same SELECT
clause.您不能在同一个
SELECT
子句中引用列别名。 Put it into a subquery.将其放入子查询中。 Also, instead of
CASE
you can use IFNULL
(or the more standard COALESCE
).此外,您可以使用
IFNULL
(或更标准的COALESCE
)代替CASE
。
SELECT eventTitle, CONCAT(eventTitle, "\n", city, ", ", state) AS title
FROM (SELECT IFNULL(session.title, course.title) AS eventTitle, session.city, session.state
FROM session
LEFT JOIN course ON course.id = session.course_id) AS subquery
Or you could just use IFNULL
twice in the same query.或者您可以在同一个查询中使用
IFNULL
两次。
SELECT IFNULL(session.title, course.title) AS eventTitle,
CONCAT(IFNULL(session.title, course.title), "\n", session.city, ", ", session.state) AS title
FROM session
LEFT JOIN course ON course.id = session.course_id
BTW, I think you either have the null check or LEFT JOIN
backwards.顺便说一句,我认为您要么进行空检查,要么向后
LEFT JOIN
。 When you use LEFT JOIN
, you get NULL
in the columns from the second table when there's no match.当您使用
LEFT JOIN
,当没有匹配项时,您会在第二个表的列中获得NULL
。 So the column that will be NULL
would be course.title
, not session.title
.因此,将为
NULL
的列将是course.title
,而不是session.title
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.