select 左连接后来自另一个 table 的列

select cols from another table after left join

在 运行 这个关于 df1 的查询之后,

"SELECT 'max' type, user, MAX(daytime) time FROM df1 UNION ALL SELECT 'min' type, user, MIN(daytime) time FROM df1")

我得到这样的结果:

type    user     time
max     a        679..
min     b        12..

我有另一个这样的数据集:

id      email
a       a@hotmail.com
b       b@hotmail.com

我想加入他们,这样我的最终结果是:

type    user     time      email
max     a        679..     a@hotmail.com
min     b        12..      b@hotmail.com

最好在同一个查询中。我试过这个:

"SELECT 'max' type, user, MAX(daytime) time FROM df1 UNION ALL SELECT 'min' type, user, MIN(daytime) time FROM df1 LEFT JOIN df2 ON df2.id == df1.user")

直到这里,它不会抛出错误,但是一旦我 select 来自 df2 的列,

"SELECT email, 'max' type, user, MAX(daytime) time FROM df1 UNION ALL SELECT 'min' type, user, MIN(daytime) time FROM df1 LEFT JOIN df2 ON df2.id == df1.user")

我得到的错误是:

PandaSQLException: (sqlite3.OperationalError) no such column: email

您必须将并集的结果作为子查询加入 df2:

SELECT t.*, df2.email 
FROM (
  SELECT 'max' type, user, MAX(daytime) time FROM df1 
  UNION ALL 
  SELECT 'min' type, user, MIN(daytime) time FROM df1 
) t LEFT JOIN df2 ON df2.id = t.user;

您只能连接两个表并将它们合并到另一个表中select

SELECT type,    df3.user,     time,      email
FROM
 (SELECT 'max' type, user, MAX(daytime) time FROM df1 UNION ALL SELECT 'min' type, user, MIN(daytime) time FROM df1) df3
LEFT JOIN df2 ON df2.id == df3.user