0

我有下表routes

from | to
---------
abc  | cde
cde  | abc
klm  | xyz
xyz  | klm
def  | ghi
ghi  | mno
mno  | ghi
ghi  | def

然后我提取每对独特的路线(在我的项目 abc -> cde = cde -> abc 中):

SELECT DISTINCT LEAST(from,to) AS point_a, GREATEST(from,to) AS point_B FROM routes

我最终得到以下结果:

point_a | point_b
-----------------
abc     | cde
klm     | xyz
def     | ghi
ghi     | mno

另外我有下表location

code | description
------------------
abc | home
cde | beach
ghi | work
xyz | club
klm | friend
...

我想将此表加入到上面的结果中,以便最终得到以下结果:

point_a | point_b | a_description | b_description
-------------------------------------------------
abc     | cde     | home          | beach
klm     | xyz     | friend        | club
...

什么查询可以一次完成所有这些?

我试图从中选择唯一的对routes然后加入表格location,或者location先加入表格然后整理重复项,我要么得到错误,要么出现重复项......

4

3 回答 3

0

您可以LEFT JOIN为此使用:

SELECT r.point_a, r.point_b
     , l1.description as a_description, l2.description as b_description
FROM 
    (SELECT DISTINCT LEAST(`from`,`to`) AS point_a
                    ,GREATEST(`from`,`to`) AS point_B 
                FROM routes) AS r
LEFT JOIN location l1
  ON r.point_a = l1.code
LEFT JOIN location l2
  ON r.point_b = l2.code;

或者INNER JOIN,如果您不想为任一点获取空值

SELECT r.point_a, r.point_b
     , l1.description as a_description, l2.description as b_description
FROM 
    (SELECT DISTINCT LEAST(`from`,`to`) AS point_a
                    ,GREATEST(`from`,`to`) AS point_B 
                FROM routes) AS r
INNER JOIN location l1
  ON r.point_a = l1.code
INNER JOIN location l2
  ON r.point_b = l2.code;

看到这个 SQLFiddle

于 2013-07-22T11:03:07.273 回答
0

一种方法:

SELECT LEAST(r.from,r.to) AS point_a, 
       GREATEST(r.from,r.to) AS point_B,
       MAX(CASE l.code WHEN LEAST(r.from,r.to) THEN l.description END) 
          a_description,
       MAX(CASE l.code WHEN GREATEST(r.from,r.to) THEN l.description END) 
          b_description
FROM routes r
JOIN location l ON l.code IN (r.from,r.to)
GROUP BY LEAST(r.from,r.to), GREATEST(r.from,r.to)

SQLFiddle在这里

于 2013-07-22T11:09:57.583 回答
0

标题具有误导性,恕我直言,它是一个 SQL 问题。但是看看UNION LEFT JOIN RIGHT JOIN运算符,你可以用它们来解决这个问题,这取决于你喜欢/想要什么。

于 2013-07-22T11:01:49.610 回答