首页 > 解决方案 > 如何在 MySQL 或 PHP 中选择 Distinct,仅用于连续值

问题描述

假设我在 MySQL 的列中有数据:

1   a
2   a
3   a
4   b
5   b
6   c
7   d
8   b
9   b
10  b
11  a

第一列是id. 如果我选择了不同的第二列,我会有

a
b
c
d

但是,如果它们没有连续或一起出现,我仍然需要这些值,即我需要:

a
b
c
d
b
a

我需要第二个“b”和第二个“a”,因为第 8、9、10 行不是“一起”或与第 4,5 行连续出现。

如何使用 MySQL 或 PHP 与 MySQL 或什至仅使用 PHP(从 csv 文件读取)来做到这一点?

注意:我使用的是 MySQL 5.6 和 PHP 7

标签: phpmysql

解决方案


This is reasonably straightforward in MySQL alone, you just need to keep track of what the last value of 'val' was and see if the current value is different. Note that to ensure the expected result, the values from table1 need to be ordered by id before being processed. Otherwise, dependent on the order of inserts you might get unexpected results...

SELECT id, @last := val AS value
FROM (SELECT * FROM table1 ORDER BY id) t
JOIN (SELECT @last := '') l
WHERE val != @last

Output

id  value
1   a
4   b
6   c
7   d
8   b
11  a

SQLFiddle Demo


推荐阅读