gpt4 book ai didi

Mysql Inner 加入 OR 条件?

转载 作者:IT老高 更新时间:2023-10-29 00:22:01 27 4
gpt4 key购买 nike

我有 2 个表,如下所示

位置_距离

----------------------------------------------
id | fromLocid | toLocid | distance
----------------------------------------------
1 | 3 | 5 | 70
2 | 6 | 8 | 15
3 | 2 | 4 | 63
...

其他表

--------------------------------------------
Id | fromLocid | toLocid | otherdata
--------------------------------------------
12 | 5 | 3 | xxxx
22 | 2 | 4 | xxxx
56 | 8 | 6 | xxxx
78 | 3 | 5 | xxxx

我想为每一行检索 other_table 中位置的黑白距离。这是我试过的

SELECT ot.*, ld.distance FROM other_table AS ot 
INNER JOIN location_distance ld ON ld.fromLocid = ot.fromLocid AND ld.toLocid = ot.toLocid

如果位置值相反,这不会返回行。我怎样才能重写上面的查询来产生预期的结果?我应该在 join 子句中包含 OR 条件吗?像下面这样?

SELECT ot.*, ld.distance FROM other_table AS ot 
INNER JOIN location_distance ld ON (ld.fromLocid = ot.fromLocid OR ld.fromLocid = ot.toLocid) AND (ld.toLocid = ot.fromLocid OR ld.toLocid = ot.fromLocid)

但是这个查询解释说“为每条记录检查范围”。 .. 这是一种不好的做法吗?

结果

--------------------------------------------------------
Id | fromLocid | toLocid | otherdata | distance
--------------------------------------------------------
22 | 2 | 4 | xxxx | 63
78 | 3 | 5 | xxxx | 70

预期结果应该是

-----------------------------------------------------
Id | fromLocid | toLocid | otherdata | distance
-----------------------------------------------------
12 | 5 | 3 | xxxx | 70
22 | 2 | 4 | xxxx | 63
56 | 8 | 6 | xxxx | 15
78 | 3 | 5 | xxxx | 70

最佳答案

您可以使用 LEFT JOIN 加入 location_distance 表两次,然后使用 COALESCE() 函数返回正确的值距离:

select ot.id,
ot.fromlocid,
ot.tolocid,
ot.otherdata,
coalesce(ld1.distance, ld2.distance) distance
from other_table ot
left join location_distance ld1
on ld1.fromLocid = ot.toLocid
and ld1.toLocid = ot.fromLocid
left join location_distance ld2
on ld2.toLocid = ot.toLocid
and ld2.fromLocid = ot.fromLocid

SQL Fiddle with Demo

这会返回结果:

| ID | FROMLOCID | TOLOCID | OTHERDATA | DISTANCE |
---------------------------------------------------
| 12 | 5 | 3 | xxxx | 70 |
| 22 | 2 | 4 | xxxx | 63 |
| 56 | 8 | 6 | xxxx | 15 |
| 78 | 3 | 5 | xxxx | 70 |

关于Mysql Inner 加入 OR 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11702294/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com