【问题标题】:from subquery reuse in where statementfrom 子查询在 where 语句中的重用
【发布时间】:2021-03-13 23:49:45
【问题描述】:

我的问题:

我想在 where 子句中重用 from 子查询中的表。我该怎么做?

select rID, name, title
from (select statement ...) as t1 
where exists(select * from t1 as t2
            where t1.ratingDate>t2.ratingDate and t1.stars>t2.stars);

这给出了一个错误:错误代码:1146。表 'sql_stanford_movie.t1' 不存在


目标: 返回 rID 使得

  • mID 和 rID 合计计数(星)=2
  • 对于给定的 mID 和 rID,最新的 ratingDate 必须有更高的星数

主表:

解决方案第 1 部分:groupby rID 和 mID 和 count==2 之后:

我创建了一个temp 表,其中包含以下内容:

select *
from Rating R1 join 
    (select rID,mID, count(mID)
    from Rating
    group by rID, mID
    having count(mID)=2) as G using(rID,mID);

解决方案的第 2 部分:检查最新的 ratingDate 是否有更高的星数

select rID, name, title
from temp as t1 
where exists(select * from temp t2
            where t1.ratingDate>t2.ratingDate and t1.stars>t2.stars);

但我需要把整个事情写在一个语句中。

【问题讨论】:

  • 您正在寻找自 MySQL 8 起可用的 WITH 子句。dev.mysql.com/doc/refman/8.0/en/with.html
  • 我没有 sql 8。我只有 5.7。 :(
  • 那太糟糕了。 MySQL 8 使许多事情成为可能。也许您可以在旧版本中实现您想要的,但这可能需要巧妙地使用变量,从而使查询难以阅读。为了简单起见,我可能只是复制该基本查询并在主查询中使用它两次。如果可以的话,升级到 MySQL 8。
  • 是的,这是一种选择,但正如您所说,可读性会变得很糟糕。谢谢。 :)

标签: mysql sql mysql-workbench


【解决方案1】:

您可以通过 CTE 做到这一点:

with t1 as (
      . . . 
     )
select rID, name, title
from t1 
where exists (select 1
              from t1 t2
              where t1.ratingDate > t2.ratingDate and 
                    t1.stars > t2.stars
             );

CTE 类似于子查询,只是您可以多次引用它。

也就是说,我猜您可以为此使用窗口函数。但是你想要的逻辑并不完全清楚。

【讨论】:

  • 嗨,逻辑上不清楚的地方......我需要遵守两件事...... 1. count(stars)==2 对于给定的rid 和mid 组合。 2.需要检查给定midrid组合的最新日期具有更高的星级。
  • 我真的很想用常规函数来做,但不知道怎么做......这就是为什么我首先做groupby并将表格“熊猫变换”为count(stars)。然后我使用简单的 where 语句来检查第二个条件。
猜你喜欢
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 2020-11-05
  • 1970-01-01
相关资源
最近更新 更多