我有一個包含關鍵字(ID,ean,關鍵字)的表和包含產品詳細信息的另一個表。我希望搜索能夠返回所有關鍵字至少匹配一次的EAN,但是我得到的最接近的是以下內容,但是例如返回的匹配項中有第一項。舉個例子,假設我有一個名爲'通用耳機 - iPhone,iPad,iPod'的產品,並且我搜索'gen%''hea%''ip%'它會作爲匹配返回,但是它也會匹配'蘋果耳機 - iPhone,iPad,iPod'由於3個IP字,這是不希望的。使用組中的所有關鍵字匹配MySQL
SQL Fiddle 我想EAN 1只匹配,所以比賽需要至少1每個術語。
任何幫助將不勝感激。
SELECT Count(keywords.ean) AS cc, products.* FROM keywords INNER JOIN products ON products.ean = keywords.ean WHERE ( keyword LIKE 'gen%' || keyword like 'ip%' || keyword LIKE 'hea%') GROUP BY (keywords.ean) HAVING cc>=3 ORDER BY `products`.`ean` ASC
更新:這會得到所需的結果,但必須有更有效的方法來做到這一點。
SELECT products.* FROM products INNER JOIN (SELECT ean, count(*) as tc1 FROM keywords WHERE (keyword like 'gen%') GROUP BY ean HAVING tc1 > 0) as t1 ON t1.ean = products.ean INNER JOIN (SELECT ean, count(*) as tc2 FROM keywords WHERE (keyword like 'ip%') GROUP BY ean HAVING tc2 > 0) as t2 ON t2.ean = products.ean INNER JOIN (SELECT ean, count(*) as tc3 FROM keywords WHERE (keyword like 'hea%') GROUP BY ean HAVING tc3 > 0 ) as t3 ON t3.ean = products.ean ORDER BY products.ean
見https://meta.stackoverflow.com/questions/333952/why-should-i -provide-an-mcve-for-what-seem-to-the-very-simple-sql-query – Strawberry
好吧,我已經用SQL小提琴更新了這篇文章。 – dt192
我認爲GregHNZ已經差不多了。只需將COUNT(*)位更改爲COUNT(DISTINCT關鍵字)= 3' – Strawberry