这是一个有效的 sql 声明吗?或者有更好的选择吗?

Is this a valid sql Statement? Or is there a better alternative for this?

sql语句是:

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

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

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

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

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`)));