2

I need i bit of help with this query, so far i have this:

SELECT * FROM coupons WHERE discount_id = '1' AND client_username = 'Zara' GROUP BY winner_id

The table is like this

id  client_username winner_id   bdate                   discount_id destroyed
72  zara            1125405534  2012-11-11 03:34:49     4            0
71  zara            1125405534  2012-11-11 03:34:43     1            0
70  zara            1125405534  2012-11-11 03:34:27     1           0

I want to group the result by winner_id (its a unique user id) where discount_id is equal to some value and order by bdate, the think is I need the id bdate and destroyed value of each ocurrence of the user and also count the number of times winner_id appear, so the result needs to be a value (count of how many times winner_id appears), and 3 arrays (discount_id,destroyed,id).. But I have no idea how to retrive this in the way I need. Thanks for any help!

4

1 に答える 1

0

Two basic methods:

  1. aggregate in mysql and "explode" in php
  2. aggregate in PHP

number 1 involves using some aggregate functions in your query, like COUNT() and GROUP_CONCAT():

SELECT count(*) as num_wins, GROUP_CONCAT(discount_id, ',') as discount_ids ...

then in PHP, these GROUP_CONCAT columns can be "exploded" into arrays while looping over the results:

foreach($rows as $row) {
  $discount_ids = explode(',', $row['discount_ids']);
  // ...
}

number 2 is easier SQL, but uglier PHP. Basically just select all your rows, and then pre-process the results yourself. (I recommend the previous solution)

foreach($rows as $row) {
  $results_tree[$row['winner_id']]['num_wins']++;
  $results_tree[$row['winner_id']]['discount_ids'][] = $row['discount_id'];
  // ...
}
于 2012-11-11T18:32:29.230 に答える