一道 sql 题目

2019-01-31 09:09:56 +08:00
 xx19941215

为何我使用的交叉连接无法通过?

select distinct `w2`.`Id` from `Weather` `w1`, `Weather` `w2`
where datediff(`w1`.`RecordDate`, `w2`.`RecordDate`) = 1
and `w2`.`Temperature` >`w1`.`Temperature`;
2136 次点击
所在节点    问与答
13 条回复
hand515
2019-01-31 09:15:16 +08:00
datediff(`w2`.`RecordDate`, `w1`.`RecordDate`) = 1

应该是反了吧?
1069401249
2019-01-31 09:20:07 +08:00
报什么错?我测试没问题啊
xx19941215
2019-01-31 09:21:21 +08:00
@hand515 哎呦 还真是 😂
Vegetable
2019-01-31 09:24:06 +08:00
弱弱的问一句这个语句时间复杂度是 O(N^2)吗?
xx19941215
2019-01-31 09:26:38 +08:00
@Vegetable cross join 就是笛卡尔积,理论上就是 O(N^2)吧 😂可能 inner join 复杂度会低点,还是我理解的都是错的?
xx19941215
2019-01-31 09:29:03 +08:00
@1069401249 你力扣提交试试 😁
Vegetable
2019-01-31 09:58:24 +08:00
@xx19941215
我觉得这种解法看起来能快一些,不过 LeetCode 里 datediff 的更快.
```
SELECT
*
FROM
Weather AS a
JOIN (SELECT * FROM Weather) AS b ON DATE_SUB(a.RecordDate, INTERVAL 1 DAY) = b.RecordDate
WHERE
a.Temperature > b.Temperature;

```
xx19941215
2019-01-31 10:06:04 +08:00
@Vegetable 我回头试试
liprais
2019-01-31 10:11:23 +08:00
@Vegetable mysql 不支持函数索引,所以这种写法要谨慎使用
Vegetable
2019-01-31 10:12:38 +08:00
@xx19941215 我试过了,的确是 datediff 快,10000 条数据的时候一个 10s 一个 15s
mwiker
2019-01-31 10:17:31 +08:00
oracle 里支持窗口函数,用这种方式效率也不错

SELECT Id
FROM (
select Id,Temperature,RecordDate,
lag(RecordDate) over(order by RecordDate) as Last_RecordDate,
lag(Temperature) over(order by RecordDate) as Last_Temperature
from Weather)
WHERE Temperature > Last_Temperature
AND RecordDate - Last_RecordDate = 1
wind3110991
2019-01-31 11:22:38 +08:00
这个天气一看就是广州了 = =
abusizhishen
2019-01-31 14:39:24 +08:00
试试把数据全拿出来,id 错一位比较温度再取 id 值

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/532036

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX