x
id id_imported_urls user_id
25041 23965 4
25040 23964 4
25039 23963 4
25037 23961 4
25034 23958 4
25033 23957 21
25032 23956 21
25031 23955 21
25030 23954 21
25029 23953 21
I’m trying to select rows, where the id_imported_urls is only present on the current user, but i cant figure out how to make the SQL call properly.
SELECT *
FROM links
WHERE id_imported_urls = 23965
AND user_id = 4
HAVING COUNT(SELECT * FROM links WHERE id_imported_urls = 23965) < 2
Advertisement
Answer
With NOT EXISTS
:
SELECT l.* FROM links l
WHERE l.id_imported_urls = 23965 AND l.user_id = 4
AND NOT EXISTS (
SELECT 1 FROM links
WHERE user_id <> l.user_id AND id_imported_urls = l.id_imported_urls
)
This will return a row only if id_imported_urls = 23965
does not exist for any user_id <> 4
.
This query:
select id_imported_urls
from links
group by id_imported_urls
having count(distinct user_id) = 1
returns all the id_imported_urls
that belong to only 1 user, so you can use it like this:
select * from links
where id_imported_urls in (
select id_imported_urls
from links
group by id_imported_urls
having count(distinct user_id) = 1
)
to get all the rows that contain these id_imported_urls
.