php - 如何在 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
解决方案
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
推荐阅读
- compilation - STM32 HAL 是否应作为预编译库包含在内
- php - after form submission display the submitted data to user in laravel
- android - 未从 Web 服务器获取数据
- mysql - MySQL:是否可以在 SELECT 语句中插入包含 OR Like?
- wso2 - wso2流处理器:流架构
- python-3.x - 我无法在 git bash 中打开 python 文件
- python - 循环遍历一个反向(列表)会增加我函数的时间复杂度吗?
- javascript - 是否有任何特定的标准或名称来记录库的端点?
- tsql - SQL:获取第一行列值不为空,否则使用第二行列
- angular - 更新组件的 HTML 后,Angular CDK 拖放将不起作用