2016-04-14 66 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