SQL JOINING主表用两个表返回记录数 - 最多其他两个表?

时间:2012-07-07 18:16:08

标签: sql join db2 left-join

我有我的MAIN表T1,我正在从中选择许多字段:

ID
1000

我有桌子T2:

ID      SERVICE
1000    IPTV
1000    VOIP

我有桌子T3:

ID      DEVICE
1000    MODEM
1000    ROUTER
1000    DVC

我想用T2或T3加入T1,但是也可能也没有值! 当他们有值时,我希望在SELECT数量的记录中有T2或T3的最大记录数。所以在这种情况下T3有3条记录是最大的,我想在SELECT中有3条记录。 (如果T2有3条记录,如果T3有2条记录则最大)

但是在我的SELECT语句中,我有5条记录,我不想要。这个的正确表达是什么?我的下面的查询返回5条记录(我想要3)

select t1.id,t2.service,t3.device
from t1
left outer join T2 on t1.id=t2.id
left outer join T3 on t1.id=t3.id

2 个答案:

答案 0 :(得分:1)

SELECT
    t1.id
  , t2.service
  , t3.device
FROM
        t1
    LEFT JOIN
            ( SELECT
                  ROW_NUMBER() OVER (PARTITION BY id ORDER BY service) AS rn
                , id
                , service
              FROM
                  t2
            ) AS t2
        FULL JOIN 
            ( SELECT
                  ROW_NUMBER() OVER (PARTITION BY id ORDER BY device) AS rn
                , id
                , device
              FROM
                  t3
            ) AS t3
          ON  t3.id = t2.id
          AND t3.rn = t2.rn
      ON COALESCE(t2.id, t3.id) = t1.id ;

答案 1 :(得分:0)

这个要求听起来不对,但以下情况应该有效

SELECT T1.*, z2.ID, z2.SERVICE FROM 
(
  SELECT ID, CASE WHEN SUM(INDICATOR) >=0 THEN 1 ELSE -1 END AS INDICATOR FROM
    (
    SELECT ID, SERVICE, 1 AS INDICATOR FROM t2
    UNION ALL
    SELECT ID , DEVICE AS SERVICE , -1 AS INDICATOR FROM t3
    ) z
  GROUP BY ID
) z1
INNER JOIN
(
  SELECT ID, SERVICE, 1 AS INDICATOR FROM t2
  UNION ALL
  SELECT ID , DEVICE AS SERVICE, -1 AS INDICATOR FROM t3
) z2
ON z1.ID = z2.ID AND z1.INDICATOR = z2.INDICATOR
RIGHT JOIN T1 ON T1.ID = Z2.ID