MySQL连接表两次没有重复数据

时间:2015-03-10 11:07:21

标签: mysql sql

SELECT SEC_TO_TIME(SUM(l1.elapsed)) AS run
FROM pattern
INNER JOIN link l1 ON l1.section = pattern.section
WHERE pattern.service = "44-A-B-y10-1" AND pattern.direction = 'outbound'

上述查询返回select语句中00:30:00值的run。我现在需要添加对link表的第二个引用。我不打算进入为什么,因为它与问题没有直接关系。

SELECT SEC_TO_TIME(SUM(l1.elapsed)) AS run
FROM pattern
INNER JOIN link l1 ON l1.section = pattern.section
INNER JOIN link l2 ON l2.section = pattern.section
WHERE pattern.service = "44-A-B-y10-1" AND pattern.direction = 'outbound'

以上是新查询。问题是,我原本希望run仍然返回00:30:00,因为它只获得SUM l1,但它现在返回32:00:00。有人可以解释为什么会这样吗?我需要保留00:30:00值,但仍然加入表格的第二个副本。

这可能吗?

架构:http://pastebin.com/0vC9pcqz

1 个答案:

答案 0 :(得分:1)

使用子查询

SELECT r1.run AS run 
FROM ( 
    SELECT pattern.section AS section, SEC_TO_TIME(SUM(l1.elapsed)) AS run
    FROM pattern
    INNER JOIN link l1 ON l1.section = pattern.section
    GROUP BY pattern.service, pattern.direction, pattern.section
    WHERE pattern.service = "44-A-B-y10-1" AND pattern.direction = 'outbound'
    ) r1
INNER JOIN link l2 ON l2.section = r1.section

如果您只想使用1行:

SELECT DISTINCT r1.run AS run 
FROM ( 
    SELECT pattern.section AS section, SEC_TO_TIME(SUM(l1.elapsed)) AS run
    FROM pattern
    INNER JOIN link l1 ON l1.section = pattern.section
    GROUP BY pattern.service, pattern.direction, pattern.section
    WHERE pattern.service = "44-A-B-y10-1" AND pattern.direction = 'outbound'
    ) r1
INNER JOIN link l2 ON l2.section = r1.section