mysql - 使用包含多个 EXIST() 语句的查询计算索引存在的次数

标签 mysql search indexing counting

我的查询根据这些产品是否存在于单独的表索引中来获取这些产品的结果。我正在尝试计算它们存在的所有实例,以便我可以按相关性对结果进行排序。我尝试的所有操作似乎都将变量@priority 返回为 0。有什么想法吗?

也许使用 join 语句更好?

感谢您的帮助。这是我的 MySQL 查询:

SELECT  `products` . * , @priority
    FROM  `products`
    LEFT JOIN productstypes_index ON productstypes_index.product_id = products.id
WHERE (

EXISTS (

SELECT *
    FROM  `productstypes_index`
    WHERE  `productstypes_index`.`product_id` =  `products`.`id`
    AND  `productstypes_index`.`_type_id` =  '1'
)
AND (
(
(

EXISTS (

SELECT @priority := COUNT( * )
    FROM  `producthashtags_index`
    WHERE  `producthashtags_index`.`product_id` =  `products`.`id`
    AND  `producthashtags_index`.`producthashtag_id` =  '43'
)
)
AND (

EXISTS (

SELECT @priority := COUNT( * )
    FROM  `producthashtags_index`
    WHERE  `producthashtags_index`.`product_id` =  `products`.`id`
    AND  `producthashtags_index`.`producthashtag_id` =  '11'
)
)
)
)
)
ORDER BY  `updated_at` DESC;

最佳答案

您可以不使用那些 exists,也可以不使用变量。此外,如果联接表上有 exists 条件,则 left join 没有任何意义。那么你不妨做更高效的inner join,将额外的类型条件放在join条件中。

可以通过哈希标签的计数来计算优先级,但仅限于 id in ('43', '11')

SELECT     products.* 
           count(distinct producthashtags_index.producthashtag_id) priority
FROM       products
INNER JOIN productstypes_index 
        ON productstypes_index.product_id = products.id
       AND productstypes_index._type_id =  '1'
INNER JOIN producthashtags_index 
        ON producthashtags_index.product_id = products.id
       AND producthashtags_index.producthashtag_id in ('43', '11')
GROUP BY   products.id  
ORDER BY   updated_at DESC;

关于mysql - 使用包含多个 EXIST() 语句的查询计算索引存在的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39551517/

相关文章:

mysql - 如何在 MYSQL 中合并记录

php - 使用mysql select的PHP block 系统出现问题

mysql - liquibase 异常未知数据类型 "JSON"

mysql - 使用 MySQL InnoDB 进行 Django 全文搜索

.net - 在 Lucene 中搜索短语

python - Pandas :更改列中 bool 索引选择的值而不会收到警告

regex - 解析多行变长日志文件

algorithm - "hill climbing"和 "branch-and-bound"搜索算法有什么区别?

java - 我在添加数组的相同索引时得到空值

python - 如何正确广播 NumPy 数组的数组索引