Simple MySQL query

Discussion in 'PHP' started by YIAM, Oct 24, 2007.

  1. #1
    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
     
    YIAM, Oct 24, 2007 IP
  2. gota

    gota Peon

    Messages:
    20
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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):
     
    gota, Oct 24, 2007 IP
    YIAM likes this.
  3. YIAM

    YIAM Notable Member

    Messages:
    2,480
    Likes Received:
    240
    Best Answers:
    0
    Trophy Points:
    280
    #3
    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.
     
    YIAM, Oct 24, 2007 IP
  4. jnestor

    jnestor Peon

    Messages:
    133
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #4
    
    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):
     
    jnestor, Oct 24, 2007 IP
    YIAM likes this.