Mysql内部连接或条件?
我有两张像下面这样的桌子 位置\u距离Mysql内部连接或条件?,mysql,subquery,inner-join,Mysql,Subquery,Inner Join,我有两张像下面这样的桌子 位置\u距离 ---------------------------------------------- id | fromLocid | toLocid | distance ---------------------------------------------- 1 | 3 | 5 | 70 2 | 6 | 8 | 15 3 | 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
其他表格
----------------------------------------------
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
我想检索每一行与其他_表中位置之间的距离。这是我试过的
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子句中加入或条件吗?像下面这样
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)
但是这个查询解释说“每个记录的检查范围”。。这种做法不好吗?
结果
预期结果应为:
像这样两次加入距离表可能会更快
INNER JOIN location_distance ld1 ON ld1.fromLocid = ot.fromLocid AND ld1.toLocid = ot.toLocid
INNER JOIN location_distance ld2 ON ld2.toLocid = ot.fromLocid AND ld2.fromLocid = ot.toLocid
然后使用IF确定要选择哪一个
IF(ld1.fromLocid, ld1.distance, ld2.distance) as distance
您可以使用
左连接在位置\u距离表上连接两次,然后使用合并()
函数返回距离的正确值:
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
看
这将返回结果:
| 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只是告诉您它使用了范围访问方法,这意味着它找到了“”,这确实是由于or.Beautiful技巧。为我工作(评论,因为没有标记为正确答案)