使用cast而不是int字段的SQL
问题描述:
当试图在开始时尝试对结果进行过滤或排序而不是使用int字段时,在where
子句中使用“带字符串字段的字符串”时是否有显着的性能结果?因为我希望meta也包含字符串值,使用cast而不是int字段的SQL
我在考虑在单独的表中分隔元字符串和元诠释,或者只是使用一个字符串表来铸造诠释值。
就像wp_postmeta的作品?
META TABLE ==
meta_id | post_id | meta_key | meta_value
1 | 101 | quantity | 8
2 | 101 | price | 100
3 | 102 | quantity | 7
4 | 102 | price | 56
5 | 103 | quantity | 12
6 | 103 | price | 256
POST TABLE ==
post_id | about
101 | Pencil | Luxurious pencil only for you
102 | Eraser | All your mistakes, gone!
103 | Pen | Unrivaled penmanship, stronger than sword.
查询:
select
p.post_id,
p.name,
p.about,
m1.meta_value,
m2.meta_value
from post_table p
inner join meta_table m1
on m1.post_id = p.post_id and m1.meta_key = 'quantity'
inner join meta_table m2
on m2.post_id = p.post_id and m2.meta_key = 'price'
where CAST(m1.meta_value as int) < 10
order by CAST(m1.meta_value as int) asc
谢谢
答
从Index documentation:不同的列(字符串列比作 时间或数字列的
比较,例如)可能会阻止索引的使用,如果 值不能直接进行比较而无需转换。
在你的情况,表达CAST(m1.meta_value as int) < 10
可能不会使用,可以用来满足该谓词,因为你没有引用在其定义的类型meta_value任何索引。
当列用于存储多类型数据(字符串,整数,日期等)时,这些是出现的问题类型。通常,对数据使用正确的数据类型可以使数据库按预期工作,并为数据库做出可以实现最佳查询执行的假设。
如果您想调整此特定查询,请考虑运行EXPLAIN select ...
并分析或发布结果。
将索引提高搜索结果,因为我使用同一列的几个值(数量,最高价格,最低价格,低价格等)? wordpress和woocommerce如何运作?过滤和分类产品 – ostrichegret