mysql - 这是一个有效的 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 的源发行版)
解决方案
让我使用文字值而不是参数,因此语法更清晰。你似乎想要:
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`)));
推荐阅读
- angular - Angular - firebase 仅在 EmailVerification 后激活/创建用户
- ios - 在谷歌地图可见区域中拟合两个地理定位点
- spring-boot - 带有弹簧靴的嵌入式 neo4j
- css - CSS使悬停覆盖活动类
- javascript - 如何触发 JQuery 选项卡元素的点击事件
- r - 按多个组计算跨多个列的最大值
- routing - 具有 Istio Ingress 的 Kubernetes 未在标准 HTTP 端口 443/80 上运行
- php - Laravel Guzzle GET 请求
- vba - 编写循环以将底部 20 行的值设置为 0
- android - 如何通过opencv实时检测人脸?