检索具有2列匹配且1个不同的行

时间:2015-12-30 08:25:48

标签: mysql sql

以下是我的表格" datapoints'。我正在尝试检索有不同“传感器值”实例的实例。对于同一时间阅读'和' sensorNumber'。

例如:

 sensorNumber sensorValue timeOfReading

      5            5           6
      5            5           6
      5            6           10   <----same time/sensor diff value!
      5            7           10   <----same time/sensor diff value!

应该输出:sensorNumber:5,timeOfReading:10作为结果。

datapoints table

我理解这是一个重复的问题,事实上我有一个下面提供的链接供参考 - 但是没有一个解决方案正常工作,因为我的查询根本就没有结束。

下面是我的SQL代码:

SELECT table1.sensorNumber, table1.timeOfReading
FROM datapoints table1
WHERE (SELECT COUNT(*)
        FROM datapoints table2
        WHERE table1.sensorNumber = table2.sensorNumber
        AND table1.timeOfReading = table1.timeOfReading 
        AND table1.sensorValue != table2.sensorValue) > 1
        AND table1.timeOfReading < 20;

注意我已经为timeOfReading设置了一个低至20的界限。我也尝试为table1和table2设置一个绑定但是查询只运行到超时而不显示结果,无论我放什么......

数据库包含大约700mb的数据,所以我认为我不能在合理的时间内在整个数据库上运行它,我想知道这是否是罪魁祸首?

如果是这样,我怎样才能正确限制查询以有效地运行搜索?如果不是这样做错了,这不起作用?

Select rows having 2 columns equal value

编辑: 错误代码:2013。查询600.000秒期间与MySQL服务器的连接丢失

当我尝试再次运行查询时,除非重新启动,否则会出现此错误 错误代码:2006。MySQL服务器已经消失了0.000秒

4 个答案:

答案 0 :(得分:2)

我想你错过了一个病情。添加非条件也只能退出具有不同值的实例。

SELECT * FROM new_table a 
where exists (select * from new_table b 
where a.num=b.num and a.timeRead=b.timeRead and a.value!=b.value);

答案 1 :(得分:2)

您可以使用自JOIN匹配同一表中的相关行。

SELECT DISTINCT t1.sensorNumber, t1.timeOfReading
FROM datapoints AS t1
JOIN datapoints AS t2 
    ON t1.sensorNumber = t2.sensorNumber
    AND t1.timeOfReading = t2.timeOfReading
    AND t1.sensorValue != t2.sensorValue
WHERE t1.timeOfReading < 20

DEMO

要提高效果,请确保您在sensorNumbertimeOfReading上有一个综合索引:

CREATE INDEX ix_sn_tr on datapoints (sensorNumber, timeOfReading);

答案 2 :(得分:0)

此查询将返回sensorNumber和timeOfReading,其中有不同的sensorValue值:

alter table tablename add index idx_sensor_time (sensorNumber, timeOfReading)

这将返回实际记录:

{{1}}

我建议你在sensorNumber,timeOfReading

上添加一个索引
{{1}}

答案 3 :(得分:0)

您可以尝试此查询

select testTable.* from testTable inner join (

SELECT sensorNumber,timeOfReading
FROM testTable
 group by sensorNumber , timeOfReading having Count(distinct sensorValue) > 1) t
 on
 t.sensorNumber = testTable.sensorNumber and t.timeOfReading = testTable.timeOfReading;

这里是sqlFiddle