简体   繁体   English

基于 3 个条件选择 3 行的最佳 MySQL 索引和查询

[英]Optimal MySQL indexes and query for selecting 3 rows based on 3 conditions

I have a MySQL table products with ~10k rows looking like this:我有一个大约 10k 行的 MySQL 表products ,如下所示:

+----+-----+--------+------+---------+
| id | cat | color  | size |  descr  |
+----+-----+--------+------+---------+
|  1 |   1 | red    |    1 | Lorem 1 |
|  2 |   1 | green  |    2 | Lorem 2 |
|  3 |   2 | orange |    1 | Lorem 3 |
|  4 |   2 | blue   |    3 | Lorem 4 |
+----+-----+--------+------+---------+

I need to select 3 specific records based on 3 conditions with a single MySQL query.我需要使用单个 MySQL 查询根据 3 个条件选择 3 个特定记录。 There are always will be exactly 3 records satisfying all 3 conditions.总会有恰好 3 条记录满足所有 3 个条件。

Here is the query I came up with that works:这是我提出的有效查询:

SELECT 
  cat, 
  color, 
  size, 
  descr 
FROM 
  products 
WHERE 
  (
    cat = 1 
    AND color = 'red' 
    AND size = 1
  ) 
  OR (
    cat = 2 
    and color = 'orange' 
    and size = 1
  ) 
  OR (
    cat = 2 
    AND color = 'blue' 
    AND size = 3
  )

Question 1: Is this the most optimal query to retrieve the 3 records based on 3 conditions?问题 1:这是基于 3 个条件检索 3 条记录的最佳查询吗?

Question 2: What would be the optimal index(s) structure for this table?问题 2:该表的最佳索引结构是什么?

Thanks in advance!提前致谢!

I'd create an index on (cat, color, size) .我会在(cat, color, size)上创建一个索引。 The order of columns in the index doesn't matter in this case, since you use = for the comparisons in all cases.在这种情况下,索引中列的顺序无关紧要,因为在所有情况下都使用=进行比较。

MySQL's IN() predicate supports row constructor comparison syntax, and current versions of MySQL do support index optimization for row constructor expressions (old versions of MySQL didn't, but those versions are all past their end-of-life by now). MySQL 的IN()谓词支持行构造函数比较语法,并且当前版本的 MySQL 确实支持行构造函数表达式的索引优化(旧版本的 MySQL 不支持,但这些版本现在都已经过时了)。

SELECT 
  category, 
  color, 
  size, 
  descr 
FROM 
  products 
WHERE (cat, color, size) IN (
    (1, 'red', 1),
    (2, 'orange', 1),
    (2, 'blue', 3)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM