【发布时间】:2012-07-07 22:27:21
【问题描述】:
假设我有如下声明
select * from table where column in (select other_column from other_table)
但我希望仅当“二进制”列等于 other_column 时才匹配。有点像“binary like”,但对于“in”运算符。
我希望问题很清楚。 谢谢:)
【问题讨论】:
假设我有如下声明
select * from table where column in (select other_column from other_table)
但我希望仅当“二进制”列等于 other_column 时才匹配。有点像“binary like”,但对于“in”运算符。
我希望问题很清楚。 谢谢:)
【问题讨论】:
根据the manual:
如果
expr等于IN列表中的任何值,则返回1,否则返回0。如果所有值都是常量,则根据expr的类型对它们进行评估并排序。然后使用二进制搜索完成对项目的搜索。这意味着如果IN值列表完全由常量组成,IN会非常快。否则,类型转换将根据Section 12.2, “Type Conversion in Expression Evaluation” 中描述的规则进行,但适用于所有参数。
当然,在您的示例中,总是可以将IN 替换为连接:
SELECT * FROM table JOIN other_table ON table.column = other_table.other_column
【讨论】:
你可以这样做:
select * from table where BINARY column in (select other_column from other_table)
或
select * from table where column in (select BINARY other_column from other_table)
但是这两者的性能会很糟糕,因为您要求 mysql 在比较之前对所有值进行类型转换。
按照另一条评论的建议,最好将查询重写为 JOIN,但是您仍然会遇到连接您正在对其进行类型转换的值的问题,并且您不能使用索引。
如果您希望对此字段进行区分大小写或精确比较,则将表中的字符集更改为 BINARY 列,或使用带有 _cs 的排序规则
像往常一样,手册会告诉你所有这些MySQL Character sets and Collations
【讨论】: