现在,我在MySQL中创建了一个表设为PinDistance,列为PinCode1PinCode2Distance.
我有一个这样的记录.
|PinCode1|PinCode2|距离|
|移动400001美元|移动400002美元|移动通信设备2移动通信设备|
|收入400004美元|收入400001美元|收入5.5亿美元|

Now I want to pass two pincodes say '400001' and '400002' and I want to Distance in response in a query such that query checks both columns and get the data.
Currently I am doing like the following
Select Distance from PinDistance where PinCode1 = '400001' and PinCode2 = '400002' - IF I get data from this then I stop here else I pass another query interchanging pincode values simultaneously.

Select Distance from PinDistance where PinCode1 = '400002' and PinCode2 = '400001'

有没有更好的办法?

推荐答案

使用操作符IN:

SELECT Distance 
FROM PinDistance 
WHERE ('400001', '400002') IN ((PinCode1, PinCode2), (PinCode2, PinCode1));

If there is a case that both combinations ('400001', '400002') and ('400002', '400001') may exist in the table and you want only 1 row as the result you can add LIMIT 1 to the query.

See the demo.

Mysql相关问答推荐

用于搜索从各种表中获得的结果的查询

为什么MySQL不考虑在联接中使用(JSON)函数索引,而考虑在生成的列上使用索引?

SQL: Select TEXT 字段的子字符串比整个值快

估计对大表进行分区所需的时间

sequelize 中最好的更新方法是什么

为什么一个 10 位的电话号码不能存储在长度为 10 的整数中?

如何在考虑另一表的值的情况下计算一列的值

如何查看 rdsadmin 在 mysql 实例上的权限?

使用case查询并更新最后一条记录

MySQL Workbench - 如何同步 EER 图

MySQL函数查找两个日期之间的工作日数

如何使用 phpmyadmin 复制数据库?

为什么数据库行元组中的整数具有L后缀?

mysql中float(2,2)和float()的区别

使用 PHP 和 MySQL 存储和显示 unicode 字符串 (हिन्दी)

在 PHP/MySQL 中将日期时间存储为 UTC

MySQL中的行值增加和减少1

如何在 MySQL 中删除此索引?

SQL WHERE 列 = 一切

为什么在 MySQL 中使用外键约束?