DISTINCT & GROUP BY on the same query.

Discussion in 'PHP' started by nitrox, Mar 20, 2010.

  1. #1
    I'm going crazy with this. Please help!!!

    Right now I have the following query:

    SELECT name, COUNT(name), time, price, ip, SUM(price) FROM tablename WHERE time >= $yesterday AND time <$today GROUP BY name
    PHP:
    And what I'd like to do is add a DISTINCT by column 'ip', i.e.

    SELECT DISTINCT ip FROM tablename 
    PHP:
    So my final output would be all the columns, from all the rows that where time is today, grouped by name (with name count for each repeating name) and no duplicate ip addresses.

    What should my query look like? (or alternatively, how can I add the missing filter to the output with php)?

    Thanks in advance.
     
    nitrox, Mar 20, 2010 IP
  2. Lordo

    Lordo Well-Known Member

    Messages:
    2,082
    Likes Received:
    58
    Best Answers:
    0
    Trophy Points:
    190
    #2
    Ummm.. Maybe you just need to add this to the end of your query and see if the result is what you need:
    , ip
     
    Lordo, Mar 21, 2010 IP
  3. waterbomm

    waterbomm Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    how about it?

    SELECT name, COUNT(name), time, price, ip, SUM(price) FROM tablename WHERE time >= $yesterday AND time <$today GROUP BY name, ip
    PHP:
     
    waterbomm, Mar 22, 2010 IP
  4. Xuhybrid

    Xuhybrid Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Do this first

    $sql = "SELECT DISTINCT ip FROM tablename";
    $query = mysql_query($sql);
    while (list($ip) = mysql_fetch_array($query))
    {
        //collect rest of the data
    }
    Code (markup):
    Then run your other query to get the rest of the data, using the ip as your identifier.
     
    Xuhybrid, Mar 23, 2010 IP