I have the following table in PostgreSQL database:
CREATE TABLE maclist (
username character varying,
mac macaddr NOT NULL,
CONSTRAINT maclist_user_mac_key UNIQUE (username, mac)
);
I need a way to check if the MAC address is assigned to the user or the user has no assigned MAC addresses at all. Basically I need a query that returns row if all conditions are true or no condition is true ie NOT a XOR b.
EDIT:
Example:
username | mac
john | 11:22:33:44:55:66
john | 11:22:33:44:55:67
doe | 11:22:33:44:55:68
If I query:
username = john, mac = 11:22:33:44:55:66 -> true, 1 whatever...
username = john, mac != 11:22:33:44:55:66 -> 0, null or nothing...
username = jane, mac = no matter what except john's or doe's -> true, 1 whatever...
username = jane, mac = john's or doe's -> 0, null or nothing...
I need true under two conditions:
- There is a row for that (user, mac) combination. There are no rows
- for that user AND there are no rows for that mac
So far I got this:
SELECT yes
FROM
(SELECT 1 AS yes) AS dummy
LEFT JOIN maclist ON (username = 'user'
OR mac = '11:22:33:44:55:66')
WHERE ((username = 'user'
AND mac = '11:22:33:44:55:66')
OR (username IS NULL
AND mac IS NULL);
It works, but it seems to me like a hack and I also have no idea about the performance of this query as the database grows.
My question is if there are any better ways to do this.
EDIT: I’ve revised the logic slightly, I think it matches what you want
The following code will return
1under two conditions…userand thatmac0rows for that user and there are0rows for thatmacUnder all other conditions, the query returns
0.userbut none of them are for thatmacmacbut none of them are for thatuser