首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel / MySQL查询raw

Laravel / MySQL查询raw
EN

Stack Overflow用户
提问于 2017-09-07 11:10:51
回答 1查看 92关注 0票数 0

不确定如何查询,但假设我有两个这样的表

表1

代码语言:javascript
复制
| id         | userid      | points       |
|:-----------|------------:|:------------:|
| 1          |      1      |     30     
| 2          |      3      |     40    
| 3          |      1      |     30     
| 4          |      3      |     40      
| 5          |      1      |     30    
| 6          |      3      |     40

表2

代码语言:javascript
复制
| 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。

目前,我有这样一个原始查询:

代码语言:javascript
复制
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连接?这是连接是适用的,然后我看到左联和其他,所以我不太确定如何去做,任何建议赞赏。

编辑:

我刚开始工作:

代码语言:javascript
复制
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%肯定的加入/左连接,如果这是可以的反馈吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-07 11:16:47

如果使用内部联接,则只得到与productid =4匹配的相关行,并仅在此求和

代码语言:javascript
复制
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上的用户,则可以使用

代码语言:javascript
复制
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 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46094872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档