mysql - 在 MySQL 查询中查找索引值必须全部存在的行

标签 mysql indexing database-indexes

我试图查找索引中存在的行,但是,即使有与我的索引匹配的行,我的结果仍然为空。我的查询逻辑有问题吗?

这是我的测试查询:

SELECT  `the_products` . * 
FROM  `the_products` 
INNER JOIN  `producttypes_index` ON  `producttypes_index`.`the_product_id` =  `the_products`.`id` 
AND  `producttypes_index`.`type_id` =  '1'
INNER JOIN  `producthashtags_index` ON  `producthashtags_index`.`the_product_id` =  `the_products`.`id` 
WHERE
`producthashtags_index`.`producthashtag_id` 
IN ('41')
AND  
`producthashtags_index`.`producthashtag_id` 
IN ('42')
AND 
`producthashtags_index`.`producthashtag_id` 
IN ('6')
ORDER BY updated_at DESC

在这里您可以看到the_product_id索引表 producthashtags_index 内存在 54433使用查询:

SELECT * 
FROM  `producthashtags_index` 
WHERE  `the_product_id` =54433

结果:

id      producthashtag_id   the_product_id
25433   6                   54433
25434   41                  54433
25435   42                  54433

然后可以看到索引表producttypes_index里面也存在它使用查询:

SELECT * 
FROM  `producttypes_index` 
WHERE  `the_product_id` =54433

结果:

type_id          the_product_id
1                54433

最佳答案

删除

AND  `producttypes_index`.`type_id` =  '1'

您还可以通过将 3 IN 变成一个来优化您的代码,如下所示:

AND  `producthashtags_index`.`producthashtag_id` IN('42','41','6')

关于mysql - 在 MySQL 查询中查找索引值必须全部存在的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751442/

相关文章:

php - 多加一张表查询统计数据SQL

mysql - 使用简单列和返回结果的聚合函数进行选择

php - CakePHP 表与另一个表有两个关系

MySQL索引顺序

sql - 使用 GIN 索引进行 Postgres 文本搜索并在其他列上对 DESC 进行排序

$elemMatch 的 MongoDB 索引

Cassandra 1.1 复合键/列和分层查询

mysql - 链接两个 MySQL 表

mysql - 给定用例的最佳 MySQL 表模式

MySQL insert, update-heavy, 按索引排序