首页 > 解决方案 > 这是一个有效的 sql 语句吗?或者有更好的选择吗?

问题描述

sql语句为:

SELECT * FROM support_chat WHERE (`from`=? AND `to`=?) OR (`from`=? AND `to`=?);

或者这个sql语句有替代方案吗?而且,这个 sql 语句是否有效(我认为是,但请告诉我)?

以防万一:
我的 MySQL 版本是 8.0.22(从https://dev.mysql.com/downloads安装,带有 boost for linux 的源发行版)

标签: mysqlsqlquery-optimizationwhere-clause

解决方案


让我使用文字值而不是参数,因此语法更清晰。你似乎想要:

where (`from` = 1 AND `to` = 2) OR (`from` = 2 AND `to` = 1)

这有效,并且(可能!)做你想做的事。您还可以表述逻辑元组相等性,这会缩短条件:

where (`from`, `to`) in ((1, 2), (2, 1))

这可能比您的原始代码更有效,特别是如果您在(from, to).

或者,如果您不想重复参数:

where (1, 2) in ((`from`, `to`), (`to`, `from`))

另一种用途least()greatest()

where least(`from`, `to`) = 1 and greatest(`from`, `to`) = 2

这将利用表达式索引,最新版本的 MySQL 支持该索引:

create index idx_support_chat on support_chat((least(`from`, `to`)), (greatest(`from`, `to`)));

推荐阅读