具有多个条件问题的SQL select查询

时间:2017-03-10 10:22:27

标签: mysql

我遇到了SQL select查询的问题,我无法弄清楚它需要什么。

这就是我items表格的样子:

| id |   i_id   |      last_seen       |   spot    |
----------------------------------------------------
| 1  |   ls100  | 2017-03-10 15:30:40  |  spot800  |
| 2  |   ls100  | 2017-03-10 16:20:15  |  spot753  |
| 3  |   ls200  | 2017-03-10 16:33:10  |  spot800  |
| 4  |   ls300  | 2017-03-10 15:30:40  |  spot800  |
| 5  |   ls300  | 2017-03-10 12:10:30  |  spot800  |
| 6  |   ls400  | 2017-03-10 10:30:10  |  spot800  |

这就是我想要获得的:

 | id |   i_id   |      last_seen       |   spot    |
 ----------------------------------------------------
 | 3  |   ls200  | 2017-03-10 16:33:10  |  spot800  |
 | 5  |   ls300  | 2017-03-10 12:10:30  |  spot800  |

所以我需要有点= 'spot800', last_seen = MAX(but only if the DateTime is the newest compared to all spots with the same i_id`)的行,最后DateTime必须大于'2017-03-10 11:00:00'。

这是我到目前为止所做的:

SELECT * 
  FROM items
 WHERE spot = 'spot800' 
HAVING MAX(`last_seen`) 
   AND `last_seen` > '2017-03-10 11:00:00' 

3 个答案:

答案 0 :(得分:2)

E.g:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,i_id   INT NOT NULL
,last_seen       DATETIME NOT NULL
,spot    INT NOT NULL
);

INSERT INTO my_table VALUES
(1,100,'2017-03-10 15:30:40',800),
(2,100,'2017-03-10 14:20:15',753),
(3,200,'2017-03-10 16:33:10',800),
(4,300,'2017-03-10 15:30:40',800),
(5,300,'2017-03-10 12:10:30',800),
(6,400,'2017-03-10 10:30:10',800);

    SELECT [DISTINCT] x.* 
      FROM my_table x
      LEFT
      JOIN my_table y
        ON y.i_id = x.i_id
       AND y.last_seen < x.last_seen
     WHERE x.last_seen > '2017-03-10 11:00:00' 
       AND x.spot = 800
       AND y.id IS NULL;
----+------+---------------------+------+
| id | i_id | last_seen           | spot |
+----+------+---------------------+------+
|  3 |  200 | 2017-03-10 16:33:10 |  800 |
|  5 |  300 | 2017-03-10 12:10:30 |  800 |
+----+------+---------------------+------+
2 rows in set (0.00 sec)

答案 1 :(得分:0)

使用MAXGROUP BY

SELECT id, i_id, MAX(last_seen), spot  
FROM items
WHERE spot = 'spot800'
AND last_seen > '2017-03-10 11:00:00'
GROUP BY id, i_id, spot

答案 2 :(得分:0)

你的陈述有几件事情。

首先, HAVING 必须附带GROUP BY子句,所以它不是你想要的。

此外,MAX是聚合,而不是布尔函数。也就是说,它不能用于过滤器,例如where子句或having子句。此外,如果它确实有效,MAX只会返回包含时间为“2017-03-10 16:33:10”的条目。不是你所期望的。

请改为尝试:

SELECT * FROM items WHERE (spot='spot800' AND last_seen > '2017-03-10 11:00:00');