mysql - 从表中选择具有重复字段的行,但优先考虑分组依据

标签 mysql database

包含列 id、order_number、位置的表格 数据看起来像

[1, 123, 'texas']
[2, 123, 'ny']
[3, 456, 'texas']
[4, 456, 'ny']
[5, 678, 'hawaii']

我想选择来自 ny 且与 texas 具有相同 order_number 的记录的 id >

最佳答案

一种选择是使用 EXISTS 子句:

SELECT id
FROM yourTable t1
WHERE location = 'ny' AND EXISTS (SELECT 1 FROM yourTable t2
                                  WHERE t1.order_number = t2.order_number AND
                                        t2.location = 'texas');

编辑:如果您想使用聚合方法,那也是可能的:

SELECT MAX(CASE WHEN location = 'ny' THEN id END) AS id
FROM yourTable
WHERE location IN ('ny', 'texas')
GROUP BY order_number
HAVING COUNT(DISTINCT location) = 2;

Demo

在这里,我们可以按 order_number 进行聚合,然后转出纽约的 id 值。

关于mysql - 从表中选择具有重复字段的行,但优先考虑分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51340814/

相关文章:

php - PHP 中的 mssql_connect 不存在

mysql - 对dbShards有意见吗?

mysql - 如何以 CakePHP 格式编写 MySQL 查询?

mysql - 如何在 Sequelize 中使用 findAll 和关联

php - 如何在PHP中的数据库中插入复选框和文件字段值

php - 在 PHP 和 MySQL 中创建带循环的嵌套数组

php - MySQL 插入语句因外键约束而失败

node.js - 将 HLS .m3u8 文件及其段文件 .ts 存储在 cassandra 数据库中是否很好?

c# - 找不到查询 'Select' 的实现未找到

java - 嵌套异常是 org.hibernate.PropertyAccessException : Could not set field value