Using group by and having clause

前端 未结 5 1277
一生所求
一生所求 2020-12-07 11:59

Using the following schema:

Supplier (sid, name, status, city)
Part (pid, name, color, weight, city)
Project (jid, name, city)
Supplies (sid, pid, jid**, qua         


        
5条回答
  •  半阙折子戏
    2020-12-07 12:11

    First of all, you should use the JOIN syntax rather than FROM table1, table2, and you should always limit the grouping to as little fields as you need.

    Altought I haven't tested, your first query seems fine to me, but could be re-written as:

    SELECT s.sid, s.name
    FROM 
        Supplier s
        INNER JOIN (
           SELECT su.sid
           FROM Supplies su
           GROUP BY su.sid
           HAVING COUNT(DISTINCT su.jid) > 1
        ) g
            ON g.sid = s.sid
    

    Or simplified as:

    SELECT sid, name
    FROM Supplier s
    WHERE (
        SELECT COUNT(DISTINCT su.jid)
        FROM Supplies su
        WHERE su.sid = s.sid
    ) > 1
    

    However, your second query seems wrong to me, because you should also GROUP BY pid.

     SELECT s.sid, s.name
        FROM 
            Supplier s
            INNER JOIN (
                SELECT su.sid
                FROM Supplies su
                GROUP BY su.sid, su.pid
                HAVING COUNT(DISTINCT su.jid) > 1
            ) g
                ON g.sid = s.sid
    

    As you may have noticed in the query above, I used the INNER JOIN syntax to perform the filtering, however it can be also written as:

    SELECT s.sid, s.name
    FROM Supplier s
    WHERE (
         SELECT COUNT(DISTINCT su.jid)
         FROM Supplies su
         WHERE su.sid = s.sid
         GROUP BY su.sid, su.pid
    ) > 1
    

提交回复
热议问题