从表中选择具有重复字段的行,但按分组的优先级

时间:2018-07-14 15:24:20

标签: mysql database

带有columns id, order_number, location的表 数据看起来像

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

我想从id中选择与ny中具有相同order_number的记录texas

1 个答案:

答案 0 :(得分:0)

一种选择是使用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值作为枢纽。