有没有办法按如下方式过滤结果:
数据集:
ID NAME VALUE
-----------------------------------------
23 Test TRUE
24 Test FALSE
25 Test FALSE
26 Test TRUE
27 Test FALSE
28 Test FALSE
结果应该是:
ID NAME VALUE
-----------------------------------------
23 Test TRUE
24 Test FALSE
26 Test TRUE
27 Test FALSE
我们的想法是返回值为TRUE的所有行以及在true
之后返回值为false的第一行答案 0 :(得分:0)
可能只有将表再次连接到同一个表时,只有这个sql的问题是它需要有不间断的ID
数据
id name value 1 TEST 1 2 TEST 0 3 TEST 0 4 TEST 0 5 TEST 1 6 TEST 1 7 TEST 0 8 TEST 0 9 TEST 1
根据下一行的ID加入同一个表,然后根据值true/1
或当前行t1.value=0
以及之前t2.value = 1
SELECT t1.* FROM table as t1
LEFT JOIN table t2 ON t1.id = t2.id + 1
WHERE ( ( t1.value = 1 ) OR ( t1.value = 0 AND t2.value = 1 ) )
ORDER BY t1.id
结果
id name value 1 TEST 1 2 TEST 0 5 TEST 1 6 TEST 1 7 TEST 0 9 TEST 1
编辑:我的最后机会,虽然不确定性能但非连续ID正在使用此
SELECT * FROM my_table as t1
LEFT JOIN my_table t2 ON
t2.id = (
SELECT MAX(my_table.id) FROM my_table
WHERE my_table.id < t1.id ORDER BY id asc LIMIT 1
)
WHERE (t1.value=1) OR (t1.value=0 AND t2.value=1) order by t1.id asc
答案 1 :(得分:0)
我想这可以通过自我加入完成,例如:
SELECT ID, NAME, VALUE
FROM table
WHERE VALUE = "TRUE"
UNION ALL
SELECT t2.ID, t2.NAME, t2.VALUE
FROM table t1
JOIN table t2
ON t1.ID +1 = t2.ID
AND t1.VALUE = "TRUE"
AND t2.VALUE = "FALSE"
编辑:这也适用于非破坏ID,因此不适用于OP案例
答案 2 :(得分:0)
E.g:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
,value TINYINT NOT NULL
);
INSERT INTO my_table VALUES
(23,'Test',TRUE),
(24,'Test',FALSE),
(25,'Test',FALSE),
(26,'Test',TRUE),
(27,'Test',FALSE),
(28,'Test',FALSE);
SELECT a.*
FROM my_table a
JOIN
( SELECT x.*
, MIN(y.id) minid
FROM my_table x
JOIN my_table y
ON y.id > x.id
AND y.value = FALSE
WHERE x.value = TRUE
GROUP
BY x.id
) b
ON a.id IN (b.id,b.minid);
+----+------+-------+
| id | name | value |
+----+------+-------+
| 23 | Test | 1 |
| 24 | Test | 0 |
| 26 | Test | 1 |
| 27 | Test | 0 |
+----+------+-------+