mysql:别名表不存在(复杂子查询)

dy1byipe  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(295)

这是一个(非常)大的查询的一部分。
错误是缺少别名“clienti\u con\u rinnovo”(表“clienti\u con\u 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
u3r8eeie

u3r8eeie1#

一种可能的解决方案是创建一个视图,这样每次执行查询时就不需要将大量数据加载到结果中。而且更容易维护,因为您可以在视图中过滤或删除不再需要的列。
例子:

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

另一张table也是这样:

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
xzabzqsa

xzabzqsa2#

我不知道你想做什么,但别名不工作的方式,你试图实现它在这里。试着用这个

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

相关问题