14

我有 2 个如下表

location_distance

----------------------------------------------
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
4

2 回答 2

13

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

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

这将返回结果:

| 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 |
于 2013-02-12T02:42:28.750 回答
4

加入距离表两次可能会更快

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
于 2012-07-28T16:55:06.567 回答