我已经发了一些相同错误的相关帖子,我已经尝试了几乎所有建议的解决方案。
以下是SQL:
SELECT Sum(h.counter1 + l.counter2) AS hour_amount
FROM (
SELECT 1
FROM xp_hour h
WHERE h.account_id = '1'
AND h.hour_date = Date('2017-03-06')
AND ((
h.from_time < Time('06:00')
AND h.till_time > Time('06:00'))
OR (
h.from_time < Time('15:00')
AND h.till_time > Time('15:00'))
OR (
h.from_time = Time('06:00')
AND h.till_time = Time('15:00'))))
UNION ALL
(
SELECT 1
FROM xp_leave l
WHERE l.account_id = '1'
AND ((
l.from_datetime < Timestamp('2017-03-06 06:00')
AND l.till_datetime > Timestamp('2017-03-06 06:00'))
OR (
l.from_datetime < Timestamp('2017-03-06 15:00')
AND l.till_datetime > Timestamp('2017-03-06 15:00')))) t_union
错误
Error: Every derived table must have its own alias
答案 0 :(得分:3)
试试这个:
SELECT SUM(h.counter1 + l.counter2) AS hour_amount
FROM (
SELECT 1
FROM xp_hour h
WHERE h.account_id = '1' AND h.hour_date = DATE('2017-03-06') AND
(
(h.from_time < TIME('06:00') AND h.till_time > TIME('06:00')) OR
(h.from_time < TIME('15:00') AND h.till_time > TIME('15:00')) OR
(h.from_time = TIME('06:00') AND h.till_time = TIME('15:00'))
)
UNION ALL
SELECT 1
FROM xp_leave l
WHERE l.account_id = '1' AND
(
(l.from_datetime < TIMESTAMP('2017-03-06 06:00') AND
l.till_datetime > TIMESTAMP('2017-03-06 06:00')) OR
(l.from_datetime < TIMESTAMP('2017-03-06 15:00') AND
l.till_datetime > TIMESTAMP('2017-03-06 15:00'))
)
) t_union
您需要将整个 UNION ALL
子查询括在括号中,而不是参与UNION ALL
操作的各个子查询。
答案 1 :(得分:1)
问题在于括号。第一个查询被解释为单独的问题,属于第一个。
试试这个:
SELECT SUM(h.counter1 + l.counter2) AS hour_amount FROM
(SELECT 1 FROM xp_hour h WHERE h.account_id = '1' AND h.hour_date = DATE('2017-03-06') AND ((h.from_time < TIME('06:00') AND h.till_time > TIME('06:00')) OR (h.from_time < TIME('15:00') AND h.till_time > TIME('15:00')) OR (h.from_time = TIME('06:00') AND h.till_time = TIME('15:00')))
UNION ALL
(SELECT 1 FROM xp_leave l WHERE l.account_id = '1' AND ((l.from_datetime < TIMESTAMP('2017-03-06 06:00') AND l.till_datetime > TIMESTAMP('2017-03-06 06:00')) OR (l.from_datetime < TIMESTAMP('2017-03-06 15:00') AND l.till_datetime > TIMESTAMP('2017-03-06 15:00'))))) t_union
我从第一个查询中删除了最后一个)
到union
答案 2 :(得分:-1)
在UNION ALL
之前为派生表的第一部分命名别名,就像你为第二部分放置t_union
一样。
例如:
(SELECT 1
FROM xp_hour h
WHERE h.account_id = '1'
AND h.hour_date = DATE('2017-03-06')
AND ((h.from_time < TIME('06:00')
AND h.till_time > TIME('06:00'))
OR (h.from_time < TIME('15:00')
AND h.till_time > TIME('15:00'))
OR (h.from_time = TIME('06:00')
AND h.till_time = TIME('15:00')))) as t_union_1