[英]SQL to get records with the same column A, but different B
Suppose we have the following table called meals
: 假设我们有下表称为
meals
:
| meal | stars | ----------------- | steak | 1 | | steak | 2 | | fish | 4 | | fish | 4 | | salad | 5 |
How can I get records with the same meal, but different stars? 如何获得同一顿饭但不同星星的记录? I need the records whose only have different stars.
我需要只有不同星星的记录。
Result for the table above should be as follows: 上表的结果应如下:
| meal | stars | ----------------- | steak | 1 | | steak | 2 |
I've tried the following query: 我尝试过以下查询:
SELECT DISTINCT t1.*
FROM meals t1
INNER JOIN meals t2 ON t1.meal = t2.meal
AND t1.stars <> t2.stars;
But it consumes too much time and some noticeable amount of memory. 但它耗费了太多时间和一些明显的内存。
The actual size of my table is: 我桌子的实际大小是:
SELECT pg_size_pretty(pg_relation_size('table_name')); pg_size_pretty ---------------- 2295 MB
So I need to come up with something else and I am asking for your help! 所以我需要拿出别的东西,我正在寻求你的帮助!
SELECT a.*
FROM meals a
INNER JOIN
(
SELECT meal
FROM meals
GROUP BY meal
HAVING COUNT(DISTINCT stars) > 1
) b ON a.meal = b.meal
OUTPUT OUTPUT
╔═══════╦═══════╗
║ MEAL ║ STARS ║
╠═══════╬═══════╣
║ steak ║ 1 ║
║ steak ║ 2 ║
╚═══════╩═══════╝
SELECT meal,stars FROM meals
GROUP BY meal,stars
HAVING count(*)=1 and meal in (
SELECT meal FROM meals
GROUP BY meal
HAVING count(*)>1 )
This should be the fastest way: 这应该是最快的方式:
SELECT *
FROM meals m
WHERE EXISTS (SELECT FROM meals WHERE meal = m.meal AND stars <> m.stars);
"Get all rows, where at least one other meal exists, with the same name but different stars." “获取所有行,其中至少有一餐存在,名称相同,但星星不同。”
Assuming NULL
values do not occur. 假设不发生
NULL
值。
A simple and faster way to achieve the same results 一种简单而快捷的方法来实现相同的结果
SELECT
m.*
FROM
meals m
JOIN meals m2 ON ( m2.meal = m.meal AND m2.stars<>m.stars)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.