Query

SQLITE:標籤和產品的問題

  • April 20, 2013

我正在尋找一種方法來創建查詢以執行以下操作:

讓我們考慮 3 個表:

  • 產品:產品列表
  • 標籤:標籤列表
  • tag_ties:用於將標籤與產品相關聯的表

讓我們考慮每個表的這種結構:

產品:

  • id (int, 自增)
  • 名稱(varchar,產品名稱)

標籤:

  • id (int 自動增量)
  • label(varchar,標籤的標籤)

標記關係:

  • id (int, 自增)
  • tag_id (int, 對標籤 id 的引用)
  • ref_id(int,對產品 ID 的引用)

我想要的是:

例如,獲取所有帶有標籤 id 10、11 和 12 的產品。

此查詢不起作用,因為它返回具有至少一個標籤的產品:

select 
   p.name as name,
   p.id as id
from 
   products p inner join tag_ties ties
on
   p.id=ties.ref_id
where
   ties.ref_id=p.id and
   ties.tag_id in (10,11,12)
group by 
   p.id
order by 
   p.name asc

嘗試這樣的事情:

select
   t1.id,
   t1.name
from
   (
   select
       p.name as name,
       p.id as id
   from
       products p inner join tag_ties ties
   on
       p.id=ties.ref_id
   where
       ties.tag_id in (10,11,12)
   ) as t1
group by
   t1.id,
   t1.name
having
   count(t1.id) = 3
order by
   t1.name asc
;

您可以使用 intersect 語句解決此問題。對每個 tag_id 進行單獨選擇並將它們與 intersects 連接起來,您將只會獲得與所有三個 tag_id 匹配的記錄。

select products.id, products.name from 
products join tag_ties
on tag_ties.ref_id = products.id
where tag_ties.tag_id = 10
intersect
select products.id, products.name from 
products join tag_ties
on tag_ties.ref_id = products.id 
where tag_ties.tag_id = 11
intersect
select products.id, products.name from 
products join tag_ties
on tag_ties.ref_id = products.id 
where tag_ties.tag_id = 12

這是一篇關於使用 intersect 的參考文章

您還可以使用臨時視圖來使它看起來更漂亮一些。

create temporary view temp_view as 
select name, products.id as id, tag_ties.tag_id as tag_id 
from products join tag_ties
on tag_ties.ref_id = products.id

select name, id from temp_view where tag_id = 10
intersect ...

引用自:https://dba.stackexchange.com/questions/7603