Search code examples
sqlpostgresqlquery-performance

SQL to get records with the same column A, but different B


Suppose we have the following table called 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!


Solution

  • 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

    ╔═══════╦═══════╗
    ║ MEAL  ║ STARS ║
    ╠═══════╬═══════╣
    ║ steak ║     1 ║
    ║ steak ║     2 ║
    ╚═══════╩═══════╝