4

假设我们有下表meals

| 餐| 明星 |
-----------------
| 牛排| 1 |
| 牛排| 2 |
| 鱼| 高分辨率照片| CLIPARTO 4 |
| 鱼| 高分辨率照片| CLIPARTO 4 |
| 沙拉| 高分辨率照片| CLIPARTO 5 |

同一餐,不同星级如何获得记录?我需要只有不同星星的记录。

上表的结果应如下所示:

| 餐| 明星 |
-----------------
| 牛排| 1 |
| 牛排| 2 |

我尝试了以下查询:

SELECT DISTINCT t1.*
FROM meals t1
INNER JOIN meals t2 ON t1.meal = t2.meal
AND t1.stars <> t2.stars;

但它消耗了太多时间和一些显着的内存量。

我的桌子的实际大小是:

选择 pg_size_pretty(pg_relation_size('table_name'));
 pg_size_pretty
----------------
 2295 MB

所以我需要想出一些别的东西,我正在寻求你的帮助!

4

4 回答 4

7
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

输出

╔═══════╦═══════╗
║ MEAL  ║ STARS ║
╠═══════╬═══════╣
║ steak ║     1 ║
║ steak ║     2 ║
╚═══════╩═══════╝
于 2013-04-03T08:51:57.437 回答
1
 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 )
于 2013-04-03T08:52:56.360 回答
0

这应该是最快的方法:

SELECT  *
FROM    meals m
WHERE   EXISTS (SELECT FROM meals WHERE meal = m.meal AND stars <> m.stars);

“获取所有行,其中至少存在另一顿饭,名称相同但星号不同。”

假设NULL值不出现。

SQL小提琴。

于 2013-04-03T11:28:28.247 回答
0

实现相同结果的简单快捷方式

SELECT  
  m.*
FROM    
  meals m
  JOIN meals m2 ON ( m2.meal = m.meal AND m2.stars<>m.stars)
于 2013-04-03T17:10:31.477 回答