简体   繁体   English

SQL 问题:内连接给我空数据集

[英]SQL problem: inner join gives me empty data set

Please have a look at this question - https://leetcode.com/problems/rising-temperature/请看看这个问题 - https://leetcode.com/problems/rising-temperature/

I went with the approach of joining the table with itself and then putting my where condition to get the data I want.我采用的方法是将表与自身连接,然后放置我的 where 条件来获取我想要的数据。 This is the query I wrote :-这是我写的查询:-

SELECT wt1.Id FROM Weather wt1 
    inner join 
Weather wt2 on wt1.id = wt2.id
WHERE wt1.Temperature > wt2.Temperature AND 
      TO_DAYS(wt1.recordDate)-TO_DAYS(wt2.recordDate)=1;

Which gives me an empty data set.这给了我一个空的数据集。

However if I don't use join, and just use the Weather table twice, it works.但是,如果我不使用 join,而只使用 Wea​​ther 表两次,它就可以工作。 My query :-我的查询:-

SELECT wt1.Id 
FROM Weather wt1, Weather wt2
WHERE wt1.Temperature > wt2.Temperature AND 
      TO_DAYS(wt1.recordDate)-TO_DAYS(wt2.recordDate)=1;

I want to know what difference the inner join makes and why it doesn't work.我想知道内部连接有什么不同以及为什么它不起作用。

The correct version of your query, which neither of the two variants is actually doing, is this:您的查询的正确版本(这两种变体都没有实际执行)是这样的:

SELECT wt1.Id
FROM Weather wt1 
INNER JOIN Weather wt2
    ON wt1.Temperature > wt2.Temperature AND 
       TO_DAYS(wt1.recordDate) - TO_DAYS(wt2.recordDate) = 1;

This uses a proper explicit self-join with your conditions.这对您的条件使用了适当的显式自联接。 Note that the wt1.id = wt2.id join condition is dubious, since assuming id is a primary key or unique column, a given record can never have two different temperature values from the same column.请注意, wt1.id = wt2.id连接条件是可疑的,因为假设id是主键或唯一列,给定的记录永远不可能有来自同一列的两个不同的温度值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM