[英]Searching multiple rows in select with left join
我有3個桌子,產品,products_tags和標簽。 一個產品可以通過products_tags表連接到多個標簽。
但是,如果我現在想搜索帶有多個標簽的產品,我將執行以下查詢:
SELECT
*
FROM
products
LEFT JOIN
products_tags
ON
products_tags.product_id = products.id
LEFT JOIN
tags
ON
products_tags.tag_id = tags.id
WHERE
tags.name = 'test'
AND
tags.name = 'test2'
這是行不通的:(。如果我刪除AND標簽.name ='test2'它就可以了。所以我只能按一個標簽進行搜索,我解釋了該查詢,並說不可能在哪里。
如何使用單個查詢搜索多個標簽?
謝謝!
您是否嘗試過類似的方法:
WHERE
(tags.name = 'test'
OR
tags.name = 'test2')
要么
WHERE
tags.name in( 'test', 'test2')
因為即使將一個產品加入多個標簽,每個標簽記錄也只有一個name
值。
您需要兩次參加test和test2:
select products.*
from products
join product_tags as product_tag1 on ...
join tags as tag1 on ...
join product_tags as product_tag2 on ...
join tags as tag2 on ...
where tag1.name = 'test'
and tag2.name = 'test2'
對於test或test2,您需要一個join和一個in子句以及一個不同的:
select distinct products.*
from products
join product_tags on ...
join tags as tags on ...
where tags.name IN('test', 'test2')
您必須對COUNT(*)進行分組,以確保同時找到全部(或許多)。 第一個查詢(PreQuery)將產品標簽表連接到標簽,並查找具有匹配標簽數量的標簽以查找...然后,將其用於連接到產品的最終列表
SELECT STRAIGHT_JOIN
p.*
FROM
( select pt.product_id
from products_tags pt
join tags on pt.tag_id = tags.id
where tags.name in ('test1', 'test2' )
group by pt.product_id
having count(*) = 2
) PreQuery
join products on PreQuery.Product_ID = Products.ID
如果要搜索同時具有“ test”和“ test2”標簽的產品,則需要分別兩次連接到product_tag和tag表。
另外,請使用內部聯接,因為您只需要具有這些標簽的產品。
例:
SELECT products.*
FROM products
INNER JOIN products_tags pt1 ON pt1.product_id = products.id
INNER JOIN products_tags pt2 ON pt2.product_id = products.id
INNER JOIN tags t1 ON t1.id = pt1.tag_id
INNER JOIN tags t2 ON t2.id = pt2.tag_id
WHERE t1.name = 'test'
AND t2.name = 'test2'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.