[英]Mysql subquery alias with exists and union all
I have a query like this:我有一个这样的查询:
SELECT '__HEADER__' as col1, 'HEADER MESSAGE' as col2
WHERE EXISTS (SELECT col1, col2,
FROM table1) long_long_query
UNION ALL
long_long_query
but seems that doesn't like the alias.但似乎不喜欢别名。 I'd like to have the header only if results are present, obviously, and not to copy/paste the long long query twice.
显然,只有当结果存在时,我才想要 header,而不是复制/粘贴长长的查询两次。 Is it possible?
可能吗?
You can't use an alias to refer to the subquery used with EXISTS
.您不能使用别名来引用与
EXISTS
一起使用的子查询。
If you want to avoid writing the query twice, you can use a Common Table Expression in MySQL 8.x:如果要避免两次编写查询,可以在 MySQL 8.x 中使用公共表表达式:
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;
Prior to 8.x you can define a view.在 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.