如何在MySQL中使用CONCAT的别名?

时间:2016-10-18 19:05:05

标签: mysql

我需要返回一个别名列eventTitle,其内容可以变化,具体取决于另一列的值是否为null。我还需要使用该别名的值来连接其他一些值以返回另一个别名title

我正在运行以下查询:

$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';

我收到以下错误:

  

未知栏' eventTitle'在'字段列表'

1 个答案:

答案 0 :(得分:4)

您不能在同一SELECT子句中引用列别名。把它放到子查询中。另外,您可以使用CASE(或更标准的IFNULL)代替COALESCE

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

或者您可以在同一查询中使用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
顺便说一句,我认为您要么进行空检查,要么向后LEFT JOIN。当您使用LEFT JOIN时,如果没有匹配项,则会从 second 表的列中获得NULL。因此,NULL的列将是course.title,而不是session.title