Mysql 存在并联合所有的子查询别名

Mysql subquery alias with exists and union all

我有这样的查询:

SELECT '__HEADER__' as col1, 'HEADER MESSAGE' as col2 
WHERE EXISTS (SELECT col1, col2,
       FROM table1) long_long_query
UNION ALL 
long_long_query

但似乎不喜欢别名。显然,我希望仅在结果存在时才使用 header,而不是两次 copy/paste 长查询。可能吗?

您不能使用别名来引用与 EXISTS 一起使用的子查询。

如果你想避免写查询两次,你可以在MySQL 8.x:

中使用Common Table Expression
WITH long_long_query AS (
    SELECT col1, col2
    FROM table1
)
SELECT SELECT '__HEADER__' as col1, 'HEADER MESSAGE' as col2 
FROM DUAL
WHERE EXISTS (SELECT * FROM long_long_query)
UNION
SELECT * FROM long_long_query;

在 8.x 之前,您可以定义一个视图。

CREATE VIEW long_long_query AS
SELECT col1, col2
FROM table1;

SELECT SELECT '__HEADER__' as col1, 'HEADER MESSAGE' as col2 
FROM DUAL
WHERE EXISTS (SELECT * FROM long_long_query)
UNION
SELECT * FROM long_long_query;