不确定如何查询,但假设我有两个这样的表
表1
| id | userid | points |
|:-----------|------------:|:------------:|
| 1 | 1 | 30
| 2 | 3 | 40
| 3 | 1 | 30
| 4 | 3 | 40
| 5 | 1 | 30
| 6 | 3 | 40表2
| id | userid | productid |
|:-----------|------------:|:------------:|
| 1 | 1 | 4
| 2 | 3 | 4
| 3 | 1 | 3
| 4 | 3 | 3
| 5 | 1 | 3
| 6 | 3 | 3我需要从表1中得到所有的s行,其中点在30以上,而table2的productid为4。
目前,我有这样一个原始查询:
SELECT userid, SUM(points) as points FROM table1 GROUP BY userid HAVING SUM(points) >= 30 ORDER BY SUM(points) DESC, userid 通过DB::选择
如何确保所有结果都只有一个产品id为4,通过table2通过用户id连接?这是连接是适用的,然后我看到左联和其他,所以我不太确定如何去做,任何建议赞赏。
编辑:
我刚开始工作:
SELECT userid, SUM(points) as points FROM table1 LEFTJOIN table2 on table1.userid = table2.userid WHERE table2.productid = '4' GROUP BY userid HAVING SUM(points) >= 30 ORDER BY SUM(points) DESC, userid 它让我回到正确的结果,但不是100%肯定的加入/左连接,如果这是可以的反馈吗?
发布于 2017-09-07 11:16:47
如果使用内部联接,则只得到与productid =4匹配的相关行,并仅在此求和
SELECT userid, SUM(points) as points
FROM table1
inner join table2 on table1.id = table2.userid and productid=4
GROUP BY userid
HAVING SUM(points) >= 30
RDER BY SUM(points) DESC, userid 或者,如果您正在寻找产品=4上的用户,则可以使用
SELECT userid, SUM(points) as points
FROM table1
inner join (
select distinct userid
from table2 where productid =4
) t on table1.id = t.userid
GROUP BY userid
HAVING SUM(points) >= 30
RDER BY SUM(points) DESC, userid https://stackoverflow.com/questions/46094872
复制相似问题