每个选定列的不同Where子句

时间:2014-11-14 22:04:24

标签: mysql join optimization

我最初有这个查询

SELECT
    MIN(CASE WHEN id = '001' THEN value END) Col1,  
    MIN(CASE WHEN id = '002' THEN value END) Col2,
    MIN(CASE WHEN id = '003' THEN value END) Col3,  
    MIN(CASE WHEN id = '004' THEN value END) Col4,
    MIN(CASE WHEN id = '005' THEN value END) Col5,  
    MIN(CASE WHEN id = '006' THEN value END) Col6

FROM table
WHERE id IN (001, 002, 003, 004, 005, 006) and

DATE(from_unixtime(t_stamp/1000)) "2014-11-12"

AND

(value > -5 OR value > 5)


GROUP BY DATE(from_unixtime(t_stamp/1000)), HOUR(from_unixtime(t_stamp/1000)), MINUTE(from_unixtime(t_stamp/1000)) DIV 60

(value > -5 OR value > 5)第一种情况(Col1)的原因我希望它只获得>的值-5,然后对于第二种情况(Col2)相同,我希望它只获得> 5的值。

现在我尝试在where子句上使用select,但它只在一列上输出值。所以我认为我稍微改变了我的查询,所以我把它改成了这样的东西我先只做了两个列,因为我想测试它。但是,一旦我点击Go,它的执行时间太长。

SELECT ROUND(t1.floatvalue,3) C1, ROUND(t2.floatvalue,3) C2


FROM table AS t1

LEFT JOIN table AS t2

ON from_unixtime(t1.t_stamp/1000) = from_unixtime(t2.t_stamp/1000)

WHERE t1.tagid = "001" AND
t2.tagid = "002"

AND t1.floatvalue > -5 AND t2.floatvalue > 5

AND from_unixtime(t1.t_stamp/1000) BETWEEN "2014-11-14 09:00:00" AND "2014-11-14 11:00:00"

GROUP BY DATE(from_unixtime(t_stamp/1000)), HOUR(from_unixtime(t_stamp/1000)), MINUTE(from_unixtime(t_stamp/1000)) DIV 60

我做的第二个查询出了什么问题?我甚至指定了开始和结束时间,但是,它花了太长时间。 (当我输入它仍然加载时)

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你想要条件聚合:

SELECT MIN(CASE WHEN id = '001' AND value > -5 THEN value END) Col1,  
       MIN(CASE WHEN id = '002' AND value > 5 THEN value END) Col2,
       MIN(CASE WHEN id = '003' THEN value END) Col3,  
       MIN(CASE WHEN id = '004' THEN value END) Col4,
       MIN(CASE WHEN id = '005' THEN value END) Col5,  
       MIN(CASE WHEN id = '006' THEN value END) Col6
FROM table
WHERE id IN (001, 002, 003, 004, 005, 006) and
      from_unixtime(t1.t_stamp/1000) BETWEEN '2014-11-14 09:00:00' AND '2014-11-14 11:00:00'
GROUP BY DATE(from_unixtime(t_stamp/1000)), HOUR(from_unixtime(t_stamp/1000)), 
         MINUTE(from_unixtime(t_stamp/1000)) DIV 60

顺便说一下,您可以将group by改为:

GROUP BY DATE_FORMAT(from_unixtime(t_stamp/1000), '%Y-%m-%d %H:00')

而且,你应该使用单引号作为日期和字符串常量,而不是双引号。双引号有效,但它们通常用于其他目的。