运行以下查询时出现错误:
SELECT MAX( DateTime )
FROM (
(
SELECT DateTime
FROM Class_Searches
)
UNION ALL (
SELECT DateTime
FROM Book_Searches
)
)
WHERE User_Email = 'bla@blah.com'
AND DateTime > NOW( ) - INTERVAL 30 DAY
我知道我需要添加别名,但我不知道在哪里
答案 0 :(得分:18)
您需要子查询的别名,并且您需要将条件应用于您合并的两个查询:
SELECT MAX(DateTime)
FROM (
SELECT DateTime
FROM Class_Searches
WHERE User_Email = 'bla@blah.com'
AND DateTime > NOW( ) - INTERVAL 30 DAY
UNION ALL
SELECT DateTime
FROM Book_Searches
WHERE User_Email = 'bla@blah.com'
AND DateTime > NOW( ) - INTERVAL 30 DAY
) AS x
或返回数据,以便您可以在外部查询中应用条件:
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 = 'bla@blah.com'
AND DateTime > NOW( ) - INTERVAL 30 DAY
答案 1 :(得分:1)
别名是指重命名某些内容,例如SELECT t.time from table t
,t
是该表的别名。在这种情况下,您需要为子查询生成的表提供别名:
SELECT MAX( ut.DateTime )
FROM (
(
SELECT DateTime
FROM Class_Searches
) cs
UNION ALL (
SELECT DateTime
FROM Book_Searches
) bs
) ut
WHERE User_Email = 'bla@blah.com'
AND ut.DateTime > NOW( ) - INTERVAL 30 DAY
但仍然无法正常工作,因为您没有从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 = 'bla@blah.com'
AND ut.DateTime > NOW( ) - INTERVAL 30 DAY
由于UNION语法,这可能仍然无法正常工作,但至少它更接近。