MySQL左联接4个具有空重复行的表

时间:2018-12-09 23:10:44

标签: mysql left-join

我一直困扰于查询,如果结果很明显,我将从结果开始倒退,然后提供更多细节。

用户跟随跟随供应商的赞助商,我正在尝试显示所有存在用户ID的赞助商供应商产品的带用户ID的产品,没有用户ID的NULL。

Desired result (userid = 1):
productid |  supplierid  |  userid
    1            1            1
    2            1            1
    3            2           Null
    4            3            1
    5            2           Null
    6            3            1

Actual result (userid = 1):
productid |  supplierid  |  userid
    1            1            1
    1            1           Null
    2            1            1
    2            1           Null
    3            2           Null
    4            3            1
    4            3           Null
    5            2           Null
    6            3            1
    6            3           Null

我的查询

SELECT product.productid, product.supplierid, usersponsor.userid FROM product 
INNER JOIN supplier ON product.supplierid = supplier.supplierid
LEFT JOIN sponsorsupplier ON sponsorsupplier.supplierid = product.supplierid
LEFT JOIN usersponsor ON usersponsor.sponsorid = sponsorsupplier.sponsorid and usersponsor.userid = 1

我有4张桌子

sponser
supplier
product
myuser

具有这两个链接表:

usersponsor
sponsorsupplier

示例表格:

myuser:userid
  1
  2
  3
  4
  5

Sponsor:sponsorid
  1
  2
  3

Supplier:supplierid
  1
  2
  3

usersponsor
userid     |   sponsorid
  1        |       1     <- user 1 follows sponsor 1
  2        |       2
  2        |       3

sponsorsupplier
sponsorid  |   supplierid
  1        |       1     <- supplys product 1,2 (sponsor 1)
  1        |       3     <- supplys product 4,6 (sponsor 1)
  2        |       2 
  2        |       1
  3        |       3     


Product
productid  |  supplierid
  1        |      1       <-
  2        |      1       <-
  3        |      2
  4        |      3       <-
  5        |      2
  6        |      3       <-

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以聚合子查询:

SELECT
    p.productid
  , p.supplierid
  , ss.userid
FROM Product p
LEFT JOIN (
        SELECT
            ss.supplierid
          , MIN( us.userid ) userid
        FROM sponsorsupplier ss
        INNER JOIN usersponsor us ON ss.sponsorid = us.sponsorid
        WHERE us.userid = 1
        GROUP BY
            ss.supplierid
    ) ss ON p.supplierid = ss.supplierid
ORDER BY
    p.productid;