SQL使用cast而不是int字段

时间:2015-11-02 03:56:48

标签: php mysql sql wordpress postgresql

在尝试过滤或排序结果而不是在开头使用int字段时,在where子句中使用'带字符串的字符串'时是否有显着的性能结果?因为我也希望meta包含字符串值,

我正在考虑在单独的表中分离元字符串和元int,或者只使用一个带有cast for int值的字符串表。

就像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

谢谢

1 个答案:

答案 0 :(得分:0)

来自Index documentation

  

不同列的比较(将字符串列与a。比较   例如,时间或数字列可能会阻止使用索引   如果没有转换,则无法直接比较值。

在您的情况下,表达式CAST(m1.meta_value as int) < 10可能不会使用任何可用于满足该谓词的索引,因为您没有在其定义的类型中引用meta_value。

当列用于存储多类型数据(字符串,整数,日期等)时,会出现这些类型的问题。通常,对数据使用正确的数据类型允许数据库按预期工作,并使数据库做出可以允许最佳查询执行的假设。

如果您想调整此特定查询,请考虑运行EXPLAIN select ...并分析或发布结果。