受@YaroslavPogrebnyak 回答启发的版本
- 它是
NULL
安全的(如果有任何机会列可以为空)
- 如果值本身有尾随零(例如 10、20、300 等),它不会中断
- 它不使用用户(会话)变量
SELECT id, CHAR_LENGTH(
SUBSTRING_INDEX(
CONCAT(day1<=>0,
day2<=>0,
day3<=>0,
day4<=>0,
day5<=>0),
'0', -1)
) trailing_zeros
FROM table1
让我们试一试:
mysql> CREATE TABLE table1 (id int, day1 int, day2 int, day3 int, day4 int, day5 int);
Query OK, 0 rows affected (0.05 sec)
mysql> INSERT INTO table1 (id, day1, day2, day3, day4, day5) VALUES
-> (1, 4, 0, 5, 0, 0),
-> (2, 2, 0, 0, 0, 0),
-> (3, 0, 1, 10, 100, 1000),
-> (4, 2, NULL, 0, 0, 0);
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT id, CHAR_LENGTH(
-> SUBSTRING_INDEX(
-> CONCAT(day1<=>0,
-> day2<=>0,
-> day3<=>0,
-> day4<=>0,
-> day5<=>0),
-> '0', -1)
-> ) trailing_zeros
-> FROM table1;
+------+----------------+
| id | trailing_zeros |
+------+----------------+
| 1 | 2 |
| 2 | 4 |
| 3 | 0 |
| 4 | 3 |
+------+----------------+
4 rows in set (0.01 sec)
这是SQLFiddle演示