簡體   English   中英

從表中選擇,其中 id 沒有用另一個 user_id 表示

[英]SELECT from table where id is not represented with another user_id

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

我正在嘗試選擇行,其中 id_imported_urls 僅存在於當前用戶上,但我無法弄清楚如何正確進行 SQL 調用。

SELECT * 
  FROM links 
 WHERE id_imported_urls = 23965 
   AND user_id = 4
HAVING COUNT(SELECT * FROM links WHERE id_imported_urls = 23965) < 2

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 
)

僅當id_imported_urls = 23965對於任何user_id <> 4不存在時,才會返回一行。
這個查詢:

select id_imported_urls
from links
group by id_imported_urls
having count(distinct user_id) = 1

返回僅屬於 1 個用戶的所有id_imported_urls ,因此您可以像這樣使用它:

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
)

獲取包含這些id_imported_urls所有行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM