2016-04-14 75 views
0

我有GET印象两个表,并加入点击MYSQL - 得到INNER数据有两个表

Product 
+----+--------+ 
| PID| brand | 
+----+--------+ 
| 1 | Ford | 
| 2 | Toyota | 
| 6 | Holden | 
+----+--------+ 

States 
+----+--------+------+--------+------------+ 
| ID | PID |CLICKS| VIEWS | DATE  | 
+----+--------+------+--------+------------+ 
| 1 | 1  | 1 | 0 | 12/12/2015| 
| 1 | 1  | 1 | 0 | 12/12/2015| 
| 2 | 2  | 1 | 0 | 12/12/2015| 
| 3 | 2  | 0 | 1 | 12/12/2015| 
| 3 | 1  | 0 | 1 | 12/12/2015| 
+----+--------+------+--------+------------+ 

我需要这样的

+--------+------+--------+ 
| PID |CLICKS| VIEWS | 
+--------+------+--------+ 
| 1  | 2 | 1 | 
| 2  | 1 | 0 | 
+--------+------+--------+ 

一些结果是这可能吗?我已经尝试过很多次了未来的故障数据

+0

使用GROUP BY进行联接。 – jarlh

+1

查找“group by”工作方式 –

+0

'SELECT stats_property.date,property.idproperty,COUNT(stats_property.clicks ='1')AS A,COUNT(stats_property.impression ='0')AS I FROM属性INNER JOIN stats_property ON property.idproperty = stats_property.idproperty group by property.idproperty,stats_property.clicks'我试试这种方式不起作用 – user1750832

回答

1
SELECT 
    PID, 
    SUM(CLICKS) as CLICKS, 
    SUM(VIEWS) as VIEWS 
FROM States 
GROUP BY PID 

如果你对所有产品

SELECT 
    Products.PID, 
    SUM(CLICKS) as CLICKS, 
    SUM(VIEWS) as VIEWS 
FROM Products 
    LEFT JOIN States ON States.PID=Products.PID 
GROUP BY Products.PID 
+0

thanx其工作 – user1750832

1

使用该由内部联接需要0。

SELECT t1.pid, sum(clicks) as CLICKS, sum(views) as VIEWS 
FROM Product as t1 INNER JOIN States as t2 ON t1.pid=t2.pid GROUP BY t1.pid 
+0

INNER JOIN是徒劳的。状态表就够了。如果所有产品都是必需的,则应使用OUTER JOIN – StanislavL