使用类似于MySQL

时间:2017-06-04 00:50:06

标签: mysql

我有一个关键字表(ID,ean,关键字)和另一个包含产品详细信息的表。我希望搜索返回所有关键字至少匹配一次的EAN,但是我得到的最接近的是以下内容,但这会返回其中包含第一个术语3次的匹配。

举一个例子,假设我有一款名为'通用耳机 - iPhone,iPad,iPod'的产品,我搜索'gen%''hea%''ip%'它会以匹配的方式回来,但它由于3个ip字,也会匹配'Apple耳机 - iPhone,iPad,iPod',这是不可取的。

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

2 个答案:

答案 0 :(得分:1)

也许你正在追求更像这样的事情......

SELECT p.ean
     , p.description
  FROM products p 
  JOIN keywords k 
    ON k.ean = p.ean
 WHERE k.keyword LIKE 'iP%'  
    OR k.keyword LIKE 'hea%' 
    OR k.keyword LIKE 'gen%' 
 GROUP
    BY p.ean
HAVING COUNT(DISTINCT CASE WHEN k.keyword LIKE 'iP%' THEN 'iP' 
                           WHEN k.keyword LIKE 'hea%' THEN 'hea'
                           WHEN k.keyword LIKE 'gen%' THEN 'gen'
                           ELSE keyword END) = 3; 

http://sqlfiddle.com/#!9/270f9/25

答案 1 :(得分:0)

这就是我在PostgreSQL中的表现。 MySQL的语法可能略有不同。

SELECT kc.cc AS cc,
       products.*
FROM products
INNER JOIN (  SELECT ean, count(*) AS cc 
                    FROM keywords
                    WHERE ( keyword like 'ip%' 
                           OR keyword like 'ai%'
                           OR keyword like 'bei%' )
                    GROUP BY ean
                    HAVING count(*) >= 3 ) AS kc
       ON kc.ean = products.ean
ORDER BY Products.ean;