这是(非常)更大查询的一部分。
错误是缺少的别名" clienti_con_rinnovo" (表" clienti_con_rinnovo"不存在)。我不需要重写查询(逻辑是正确的)但可能有助于获得别名。
如果感兴趣(但您知道),订单为LEFT JOIN
,并且跟随UNION
。
提前谢谢
SELECT * FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE
renew IS NOT NULL
GROUP BY id ) AS clienti_con_rinnovo
UNION
SELECT * FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE renew IS NULL
GROUP BY id ) AS clienti_senza_rinnovo
LEFT JOIN clienti_con_rinnovo ON clienti_con_rinnovo.id = clienti_senza_rinnovo.id
WHERE clienti_con_rinnovo.id IS NULL
答案 0 :(得分:0)
一种可能的解决方案是创建一个视图,因此每次执行该查询时都不需要将大量数据加载到结果中。也更容易维护,因为您可以在视图内部进行过滤或删除不再需要的列。
示例:
CREATE VIEW clienti_con_rinnovo
AS
SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE
renew IS NOT NULL
GROUP BY id
但你的尝试几乎正常。尝试:
SELECT clienti_con_rinnovo.* FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE
renew IS NOT NULL
GROUP BY id ) AS clienti_con_rinnovo
和你的另一张桌子相同:
SELECT clienti_senza_rinnovo.* FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE renew IS NULL
GROUP BY id ) AS clienti_senza_rinnovo
答案 1 :(得分:0)
我不确定你要做什么,但别名不会像你在这里尝试实现的那样工作。 尝试使用此
SELECT * FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE
renew IS NOT NULL
GROUP BY id ) AS clienti_con_rinnovo_new
UNION
SELECT clienti_senza_rinnovo.* FROM
( SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE
renew IS NOT NULL
GROUP BY id ) AS clienti_con_rinnov
LEFT JOIN
(SELECT
id,
MAX(dateTransaction) AS last_transaction_renew
FROM transactions
WHERE renew IS NULL
GROUP BY id ) AS clienti_senza_rinnovo ON clienti_con_rinnovo.id =
clienti_senza_rinnovo.id
WHERE clienti_con_rinnovo.id IS NULL