我被一个查询困住了,我将从结果开始,以防这是显而易见的,然后提供更多的细节。
用户跟踪一个跟踪供应商的赞助者,我试图显示所有带有用户标识的产品,对于存在用户标识的赞助者产品,如果没有用户标识,则为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
我有四张table
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条答案
按热度按时间qoefvg9y1#
可以聚合子查询: