2016-11-29 50 views
0

我有一個MySQL數據庫與一個名爲數據表,MYSQL選取時間之間返回行早於查詢

mysql> describe data; 
+-------+---------------------+------+-----+-------------------+----------------+ 
| Field | Type    | Null | Key | Default   | Extra   | 
+-------+---------------------+------+-----+-------------------+----------------+ 
| idx | int(11)    | NO | PRI | NULL    | auto_increment | 
| ts | timestamp   | NO |  | CURRENT_TIMESTAMP |    | 
| id | tinyint(3) unsigned | NO |  | NULL    |    | 
| value | decimal(10,2)  | YES |  | NULL    |    | 
+-------+---------------------+------+-----+-------------------+----------------+ 

當我嘗試選擇一個特定的日期範圍,例如,今天,該查詢返回數據超出日期範圍。

mysql> SELECT * FROM data WHERE ts BETWEEN '2016-11-27 00:11:00' AND '2016-11-29 00:11:00' AND id LIKE '0' OR id LIKE '1' ORDER BY ts ASC LIMIT 10; 
+-------+---------------------+----+-------+ 
| idx | ts     | id | value | 
+-------+---------------------+----+-------+ 
| 14117 | 2016-11-12 15:24:16 | 1 | 0.00 | 
| 20144 | 2016-11-16 20:03:50 | 1 | 56.00 | 
| 20147 | 2016-11-16 20:04:10 | 1 | 52.00 | 
| 20150 | 2016-11-16 20:05:10 | 1 | 52.00 | 
| 20153 | 2016-11-16 20:06:11 | 1 | 52.00 | 
| 20156 | 2016-11-16 20:07:11 | 1 | 52.00 | 
| 20159 | 2016-11-16 20:08:17 | 1 | 52.00 | 
| 20162 | 2016-11-16 20:09:18 | 1 | 52.00 | 
| 20165 | 2016-11-16 20:10:21 | 1 | 52.00 | 
| 20168 | 2016-11-16 20:11:27 | 1 | 52.00 | 
+-------+---------------------+----+-------+ 

我很新的MYSQL,所以希望這是一件很容易解決,但我一直沒能找到解決方案(不缺乏嘗試)。

+2

'AND'的優先級高於'OR'。例如,表達式**'a AND b或c ** **相當於**'(a AND b)或c **。使用parens來指定操作的順序,即**'a AND(b或c)'**。 – spencer7593

回答

2

問題是OR。您可以使用圓括號,或者只使用IN

SELECT * 
FROM data 
WHERE ts BETWEEN '2016-11-27 00:11:00' AND '2016-11-29 00:11:00' AND 
     id IN (0, 1) 
ORDER BY ts ASC 
LIMIT 10;