结合Mysql子查询

时间:2017-08-04 21:52:04

标签: php mysql

我有一张产品表。使用3个不同的查询执行搜索以获得最匹配的结果。但是我得到了很少的耻辱,例如分页,因此需要将我的3个查询合并为一个并仍然给出相同的结果。

这是我的查询和每个人做什么的解释

查询1:此查询与搜索字符串完全匹配

SELECT *, 
       MATCH (product_name) AGAINST ('k' IN BOOLEAN MODE) as distance, 
       MATCH (product_description) AGAINST ('k' IN BOOLEAN MODE) as distance2 
FROM  products 
INNER JOIN shops ON shops.shop_id = products.shop_id 
WHERE MATCH  (product_name) AGAINST ('k') 
   OR MATCH (product_description) AGAINST ('k') 
ORDER BY distance DESC, distance2 DESC 
LIMIT 0, 9;

查询2:此查询获取搜索字符串是字符串一部分的所有结果减去查询结果然后将结果添加到数组

SELECT * 
FROM products 
INNER JOIN shops ON shops.shop_id = products.shop_id 
WHERE product_name LIKE '%k%' 
ORDER BY INSTR(product_name,'k'), product_name 
LIMIT 0, 9;

查询3:此查询与搜索字符串最接近,减去查询1的结果,查询2将结果添加到数组

SELECT *, 
      fuzzy_substring( 'k', product_name ) as distance, 
      fuzzy_substring( 'k', product_description ) as distance2 
 FROM products 
 INNER JOIN shops ON shops.shop_id = products.shop_id 
 WHERE (fuzzy_substring( 'k', product_name ) < 3 
    OR fuzzy_substring( 'k', product_description ) < 3) 
   AND product_id NOT IN ('pr933j4', 'Posr49il', 'p4021dd') 
 order by distance ASC, distance2 ASC 
 LIMIT 0, 9;

我无法弄清楚如何将这三个查询合并为一个对正确方向的任何建议都受到高度赞赏。 注意&#39; k&#39;是被搜索的字符串

1 个答案:

答案 0 :(得分:1)

UNION为我工作

SELECT * FROM 
 ( (SELECT j1.* FROM products AS j1 LEFT JOIN shops AS z1 ON z1.shop_id = 
    j1.shop_id WHERE MATCH (product_name) AGAINST ('k') OR MATCH 
    (product_description) AGAINST ('k') ORDER BY MATCH (product_name) 
    AGAINST ('k' IN BOOLEAN MODE) DESC, MATCH (product_description) AGAINST 
    ('k' IN BOOLEAN MODE) DESC ) s1)

UNION 

SELECT * FROM 
 ( ( SELECT j2.* FROM products AS j2 LEFT JOIN shops AS z2 ON 
    z2.shop_id = j2.shop_id WHERE product_name LIKE '%k%' ORDER BY 
    INSTR(product_name,'k'), product_name ) s2)

UNION 

SELECT * FROM 
 ( ( SELECT j3.* FROM products as j3 LEFT JOIN shops as z3 ON z3.shop_id = 
    j3.shop_id WHERE (fuzzy_substring( 'k', product_name ) < 3 OR 
    fuzzy_substring( 'k', product_description ) < 3) AND product_id NOT IN 
    ('pr933j4', 'Posr49il', 'p4021dd') order by fuzzy_substring( 'k', 
    product_name ) ASC, fuzzy_substring( 'k', product_description ) ASC ) 
    s3)