2016-03-23 53 views
1
SELECT 
'1' AS SITE 
, 'test_id' AS ID 
, IFNULL(PREV_DATA, 60) AS PREV_DATA 
, IFNULL(PREV_DATA + 2, 60 + 2) AS DATA 
FROM 'TABLE' 
WHERE ID = 'test_id' 
ORDER BY CREATE_DATE DESC 
LIMIT 1; 

即使沒有找到任何行,我也只需要一行。
而順序是非常重要的。
我試過COUNT(1)或MAX(1),但結果沒有按create_date排序...
請大家幫忙。如果在訂單中找不到行,則mysql選擇一行

-----加樣品DATA

 
+------+---------+-----------+------+---------------------+ 
| SITE | ID | PREV_DATA | DATA |  CREATE_DATE  | 
+------+---------+-----------+------+---------------------+ 
| 1 | test_id |  60 | 62 | 2016-03-21 00:00:00 | 
| 1 | test_id |  62 | 64 | 2016-03-21 10:00:00 | 
| 1 | test_22 |  60 | 62 | 2016-03-24 00:00:00 | 
+------+---------+-----------+------+---------------------+

我想下面數據當ID是 '爲test_id'。

+------+---------+-----------+------+ 
| SITE | ID | PREV_DATA | DATA | 
+------+---------+-----------+------+ 
| 1 | test_id |  64 | 66 | 
+------+---------+-----------+------+

而且我想下面的數據當ID是「test33333」

+------+-----------+-----------+------+ 
| SITE | ID  | PREV_DATA | DATA | 
+------+-----------+-----------+------+ 
| 1 | test33333 |  60 | 62 | 
+------+-----------+-----------+------+
+0

什麼是你的表結構? –

+0

數據樣本也有幫助。 –

回答

0

直視UNION ..所以你毗額外的預定義或「空白」行,但與限制1,只有它顯示在另一行未找到

像這樣(未經):

SELECT 
'1' AS SITE 
, 'test_id' AS ID 
, IFNULL(PREV_DATA, 60) AS PREV_DATA 
, IFNULL(PREV_DATA + 2, 60 + 2) AS DATA 
, CREATE_DATE 
FROM 'TABLE' 
WHERE ID = 'test_id' 
union 
SELECT 
'0' AS SITE 
, '' AS ID 
, '' AS PREV_DATA 
, '' AS DATA 
, DATE_SUB(NOW(), INTERVAL -300 YEAR) as CREATE_DATE 

ORDER BY CREATE_DATE DESC 
LIMIT 1; 
相關問題