SQL获取具有相同列A但不同B的记录

时间:2013-04-03 08:50:32

标签: sql postgresql query-performance

假设我们有一个名为meals的表:

| meal  | stars |
-----------------
| steak |   1   |
| steak |   2   |
| fish  |   4   |
| fish  |   4   |
| salad |   5   |

如何获得同一顿饭但不同星星的记录?我需要只有不同星星的记录。

上表的结果应如下:

| meal  | stars |
-----------------
| steak |   1   |
| steak |   2   |

我尝试过以下查询:

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

但它耗费了太多时间和一些明显的记忆。

我的桌子的实际大小是:

SELECT pg_size_pretty(pg_relation_size('table_name')); 
 pg_size_pretty 
----------------
 2295 MB

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

4 个答案:

答案 0 :(得分: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 ║
╚═══════╩═══════╝

答案 1 :(得分: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 )

答案 2 :(得分:0)

这应该是最快的方式:

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

&#34;获取所有存在至少另一餐的行,名称相同但不同的星星。&#34;

假设没有NULL值。

SQL Fiddle.

答案 3 :(得分:0)

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

SELECT  
  m.*
FROM    
  meals m
  JOIN meals m2 ON ( m2.meal = m.meal AND m2.stars<>m.stars)