查询以在另一个查询上加入表

时间:2013-07-22 10:54:45

标签: mysql sql duplicates

我有下表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,然后将重复的内容整理出来,我或者得到错误或者重复出现......

3 个答案:

答案 0 :(得分:0)

标题是误导性的,它更像是一个SQL问题imho。 但是看看UNION LEFT JOIN RIGHT JOIN运算符,您可以解决所有这些问题,具体取决于您喜欢/想要的内容。

答案 1 :(得分: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;

请参阅this SQLFiddle

答案 2 :(得分: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 here