简体   繁体   中英

MYSQL - Get data from INNER JOIN with two tables

I Have two tables for get impression and click

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|
+----+--------+------+--------+------------+

I need to get some result like this

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

is it possible? i have tried too many times its coming faults data

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

If you need 0 for all Products

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

Use this by Inner Join.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM