Let I have two tables Table 1 ------- name | value a1 | 5 a2 | 10 a1 | 15 a3 | 7 a3 | 8 Table 2 -------- name | price a1 | 5 a2 | 10 a1 | 15 a3 | 7 a1 | 8 I want to get result like this name | total value | total price a1 |20 | 28 a2 |10 | 10 a3 |15 | 07
something like... -- tables CREATE TABLE table1 ( `name` varchar(10) NOT NULL, `value` int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; INSERT INTO table1 VALUES ('a1', 5); INSERT INTO table1 VALUES ('a2', 10); INSERT INTO table1 VALUES ('a1', 15); INSERT INTO table1 VALUES ('a3', 7); INSERT INTO table1 VALUES ('a3', 8); CREATE TABLE table2 ( `name` varchar(10) NOT NULL, price int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; INSERT INTO table2 VALUES ('a1', 5); INSERT INTO table2 VALUES ('a2', 10); INSERT INTO table2 VALUES ('a1', 15); INSERT INTO table2 VALUES ('a3', 7); INSERT INTO table2 VALUES ('a1', 8); -- query SELECT a.name, SUM(distinct a.value) AS value, SUM(distinct b.price) AS price FROM table1 AS a INNER JOIN table2 AS b ON(a.name = b.name) GROUP BY a.name ORDER BY a.name; Code (markup):
Thanks gota, given you some green reps, this is very closed to what I'm looking for. Only problem is that if in 2nd table, we doesn't enter any value for a2 then in result table a2 row is not showing.
SELECT a.name, SUM(distinct a.value) AS value, SUM(distinct b.price) AS price FROM table1 AS a LEFT JOIN table2 AS b ON(a.name = b.name) GROUP BY a.name ORDER BY a.name; Code (markup):