![](/img/trans.png)
[英]Update Row Fields if POST['submitted_field'] Is Not Null MariaDB , MySQL
[英]MariaDB/MySQL: combine rows if fields are NULL
假設我有一個包含6行的表,第一個是自動遞增的數字ID,第二個是DateTime(自動設置),最后四個是傳感器值:
ID DateTime Val1 Val2 Val3 Val4
1 xxx 20 10 NULL NULL
2 xxx NULL NULL 30 15
3 xxx 23 14 NULL NULL
4 xxx 25 04 NULL NULL
5 xxx 12 11 NULL NULL
6 xxx NULL NULL 33 19
通常,傳感器數據會自動寫入數據庫。 也許一天幾次將手動數據添加到Val3和Val4。 現在,我必須從數據庫中加載最新行。 如果我這樣做:
SELECT Val1,Val2,Val3,Val4 FROM table ORDER BY ID DESC LIMIT 1
我得到的是Val1和2或3和4的一行。盡管我需要這種方式,但請參考上述示例:
5 | xxx | 12 | 11 | 30 | 15
or
6 | xxx | 12 | 11 | 33 | 19
最新行中的值+最后一行中具有非NULL值的缺失值。 有人這么善良地解釋如何做到這一點嗎? 在Raspberry Pi 3上運行MariaDB 10數據庫。
我將很少修改您的查詢,如下所示:
SELECT Val1,Val2,Val3,Val4 FROM table where (Val3 and Val4) is not null ORDER BY ID DESC LIMIT 1
希望這可以幫助...!!!
這種查詢需要一些可變技巧,以便回頭看最后一行。
為了更具體地顯示解決方案:
MariaDB [test] create table test2 (
id int primary key not null auto_increment,
ts timestamp not null default current_timestamp,
val1 int,val2 int,val3 int,val4 int
);
Query OK, 0 rows affected (0.43 sec)
MariaDB [test] insert into test2 (val1,val2,val3,val4) values
(20,10,null,null),
(null,null,40,25),
(23,14,null,null),
(25,4,null,null),
(12,11,null,null),
(null,null,33,19);
Query OK, 6 rows affected (0.07 sec)
Records: 6 Duplicates: 0 Warnings: 0
MariaDB [test] select * from (
select t.id as id, t.ts,
@val1 := coalesce(t.val1,@val1) as val1,
@val2 := coalesce(t.val2,@val2) as val2,
@val3 := coalesce(t.val3,@val3) as val3,
@val4 := coalesce(t.val4,@val4) as val4
from test2 t, (select @val1 := 0,@val2:=0,@val3:=0,@val4:=0) as start order by id
) x ;
+----+---------------------+------+------+------+------+
| id | ts | val1 | val2 | val3 | val4 |
+----+---------------------+------+------+------+------+
| 1 | 2017-09-20 06:53:41 | 20 | 10 | 0 | 0 |
| 2 | 2017-09-20 06:53:41 | 20 | 10 | 40 | 25 |
| 3 | 2017-09-20 06:53:41 | 23 | 14 | 40 | 25 |
| 4 | 2017-09-20 06:53:41 | 25 | 4 | 40 | 25 |
| 5 | 2017-09-20 06:53:41 | 12 | 11 | 40 | 25 |
| 6 | 2017-09-20 06:53:41 | 12 | 11 | 33 | 19 |
+----+---------------------+------+------+------+------+
6 rows in set (0.01 sec)
下面的查詢將解決您的問題。
SELECT
(SELECT Val1 FROM table where Val1 IS NOT NULL ORDER BY ID DESC LIMIT 1) as Val1,
(SELECT Val2 FROM table where Val2 IS NOT NULL ORDER BY ID DESC LIMIT 1) as Val2,
(SELECT Val3 FROM table where Val3 IS NOT NULL ORDER BY ID DESC LIMIT 1) as Val3,
(SELECT Val4 FROM table where Val4 IS NOT NULL ORDER BY ID DESC LIMIT 1) as Val4;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.