MySQL 每个派生表必须有自己的别名错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3436009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:47:07  来源:igfitidea点击:

Every derived table must have its own alias error

sqlmysql

提问by bgcode

I get that error when running the following query:

运行以下查询时出现该错误:

SELECT MAX( DateTime )
FROM (
(
    SELECT DateTime
    FROM Class_Searches
)
UNION ALL (
    SELECT DateTime
    FROM Book_Searches
)
)
WHERE User_Email = '[email protected]'
AND DateTime > NOW( ) - INTERVAL 30 DAY 

I know I need to add Aliases but I'm not sure where

我知道我需要添加别名,但我不确定在哪里

回答by Guffa

You need an alias for the subquery, and you need to apply the conditions either to both queries that you union:

您需要子查询的别名,并且您需要将条件应用于您联合的两个查询:

SELECT MAX(DateTime)
FROM (

  SELECT DateTime
  FROM Class_Searches
  WHERE User_Email = '[email protected]'
  AND DateTime > NOW( ) - INTERVAL 30 DAY

  UNION ALL

  SELECT DateTime
  FROM Book_Searches
  WHERE User_Email = '[email protected]'
  AND DateTime > NOW( ) - INTERVAL 30 DAY

) AS x

or return data so that you can apply the condition in the outer query:

或返回数据,以便您可以在外部查询中应用条件:

SELECT MAX(DateTime)
FROM (

  SELECT DateTime, User_Email
  FROM Class_Searches

  UNION ALL

  SELECT DateTime, User_Email
  FROM Book_Searches

) AS x
WHERE User_Email = '[email protected]'
AND DateTime > NOW( ) - INTERVAL 30 DAY

回答by zebediah49

An alias is when you rename something, like SELECT t.time from table t, tis the alias for that table. In this case, you need to give an alias to the tables generated by the subqueries:

别名是当您重命名某些内容时,例如SELECT t.time from table tt是该表的别名。在这种情况下,您需要为子查询生成的表指定别名:

SELECT MAX( ut.DateTime )
FROM (
(
    SELECT DateTime
    FROM Class_Searches
) cs
UNION ALL (
    SELECT DateTime
    FROM Book_Searches
) bs
) ut
WHERE User_Email = '[email protected]'
AND ut.DateTime > NOW( ) - INTERVAL 30 DAY 

That still won't work though, because you don't have a User_Email column returned from the UNION. Thus, try:

但这仍然不起作用,因为您没有从 UNION 返回的 User_Email 列。因此,尝试:

SELECT MAX( ut.DateTime )
FROM (
(
    SELECT DateTime, User_Email
    FROM Class_Searches
) cs
UNION ALL (
    SELECT DateTime, User_Email
    FROM Book_Searches
) bs
) ut
WHERE ut.User_Email = '[email protected]'
AND ut.DateTime > NOW( ) - INTERVAL 30 DAY

It's possible that that still won't work right because of the UNION syntax, but at least it's a lot closer.

由于 UNION 语法,这可能仍然无法正常工作,但至少它更接近。