每个派生表必须有自己的别名join mysql [duplicate]

2ul0zpep  于 2022-11-21  发布在  Mysql
关注(0)|答案(3)|浏览(131)

此问题在此处已有答案

What is the error "Every derived table must have its own alias" in MySQL?(4个答案)
2天前关闭。
在mysql我看到这个错误,但可以修复它。任何人都可以帮助吗?

select * from 
    (
    (select a.* from sessions as a)
    join
    (
     select b.customer_id, min(b.timestamp), 
     b.marketing_source as first_touch_source, 
     b.marketing_medium as first_touch_medium 
     from sessions as b
     group by b.customer_id
     ) on a.customer_id = b=customer_id
    ) as T
kxeu7u2r

kxeu7u2r1#

我认为您的问题应该是

select * 
from (
    select a.* 
    from sessions as a
    join
        (select b.customer_id, min(b.timestamp), b.marketing_source as first_touch_source, b.marketing_medium as first_touch_medium 
        from sessions as b
        group by b.customer_id
    ) c USING (customer_id) # or c.customer_id = a.customer_id
) as T
wn9m85ua

wn9m85ua2#

  • 如果你只是想把最小日期列,你可以尝试两种方法,第二种方法将工作,如果你的版本支持windows功能
  • 子查询总是很混乱,所以我建议使用cte(如果支持的话

第一个

xvw2m8pv

xvw2m8pv3#

一些DBMS要求您命名所有派生表。您的查询(我删除了不必要的派生表T):

select * 
from (select a.* from sessions as a)
join (select b.customer_id, min(b.timestamp)
           , b.marketing_source as first_touch_source
           , b.marketing_medium as first_touch_medium 
      from sessions as b
      group by b.customer_id
     )
  on a.customer_id = b=customer_id

可更改为:

select * 
from (select a.* from sessions as a) AS c
join (select b.customer_id, min(b.timestamp)
           , b.marketing_source as first_touch_source
           , b.marketing_medium as first_touch_medium 
      from sessions as b
      group by b.customer_id
     ) AS d
  on c.customer_id = d.customer_id

为避免混淆,应在外部级别选择另一个别名,尽管内部别名在那里不可见。
附注:衍生表格d可能是也可能不是有效的SQL。SQL92中不允许使用衍生表格d,但如果marketing_* 在功能上相依于customer_id,则SQL99中允许使用衍生表格d。
您可以进一步将其简化为:

select * 
from sessions AS c
join (select b.customer_id, min(b.timestamp) as ts
           , b.marketing_source as first_touch_source
           , b.marketing_medium as first_touch_medium 
      from sessions as b
      group by b.customer_id
     ) AS d
  on c.customer_id = d.customer_id

我假设您还想使用c.timestamp = d.ts进行连接。如果是这种情况,并且您使用的是最新版本的MySQL(8+),则可以使用窗口函数而不是自连接

select customer_id, ...
from (
    select b.customer_id
         , b.marketing_source
         , b.marketing_medium
         , row_number() over (partition by customer_id
                              order by b.timestamp) as rn 
    from sessions as b
) as T
where rn = 1

相关问题