Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL HAVING COUNT and JOIN

Tags:

sql

dml

I have tried to this query: What are the doctors that work on less than 2 Hospitals. But the result isn't what I expected.

I have these tables:

CREATE TABLE Hospital (
    hid INT PRIMARY KEY,
    name VARCHAR(127) UNIQUE,
    country VARCHAR(127),
    area INT
);
CREATE TABLE Doctor (
    ic INT PRIMARY KEY,
    name VARCHAR(127),
    date_of_birth INT,
);
CREATE TABLE Work (
    hid INT,
    ic INT,
    since INT,
    FOREIGN KEY (hid) REFERENCES Hospital (hid),
    FOREIGN KEY (ic) REFERENCES Doctor (ic),
    PRIMARY KEY (hid,ic)
);

I tried with this:

SELECT DISTINCT D.ic 
    FROM Doctor D, Work W 
    JOIN Hospital H ON (H.hid = W.hid)
    WHERE D.bi = W.bi
    GROUP BY (D.ic)
    HAVING COUNT(H.hid) < 2
;    

Thanks.

like image 234
tomss Avatar asked Oct 18 '25 11:10

tomss


1 Answers

You need to use LEFT JOIN and joining with table Hospital isn't necessary

SELECT  a.name
FROM    Doctor a
        LEFT JOIN `Work` b
            ON a.ic = b.ic
GROUP BY a.name
HAVING COUNT(b.ic) < 2
like image 164
John Woo Avatar answered Oct 21 '25 00:10

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!