Laravel / MySQL查询原始

时间:2017-09-07 11:10:52

标签: mysql laravel eloquent

不确定如何查询,但我们说我有两张桌子

表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获取所有行,其中点数大于30且table2的产量为4

目前我有这样的原始查询:

SELECT userid, SUM(points) as points FROM table1 GROUP BY userid HAVING SUM(points) >= 30 ORDER BY SUM(points) DESC, userid 

通过DB :: select

如何确保所有结果只有通过userid连接的table2的产品ID为4?这是加入是适用的地方,然后我看到leftjoin和其他人所以我不太确定如何去做这个,任何建议表示赞赏。

编辑:

我刚刚开始工作:

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%肯定加入/ leftjoin,任何反馈如果可以吗?

1 个答案:

答案 0 :(得分:0)

如果您使用内部联接,则只能获得与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