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!
Two basic methods:
aggregate in mysql and "explode" in php
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'];
// ...
}
Related
I have the following code :
$foo = $bdd->prepare($qry);
$foo->execute();
$result = $foo->fetchAll();
In $qry, i have a SELECT with a JOIN between tables beatles b et status s (on the columns status_id), such that the result is the following :
Code :
b.id b.firstname b.lastname b.status_id s.status_id s.status
0 John Lennon 0 0 Mort
1 Paul McCartney 1 1 Vivant
2 Ringo Starr 1 1 Vivant
3 George Harrison 0 0 Mort
(The first line is the columns' names in the tables, it isn't inside the result of the query)
I want to select in php only the s.status of ringo starr, for instance. How can I do that ?
Thanks
If you want to retrieve the value of status for Ringo Starr, but need the values of the other fields within that page, then (assuming the array has come back indexed by id), you could access it with $result[2]['status']. Otherwise, change your select statement to just select the values of id and status.
As a side note, in your SELECT statement you'll need to give aliases potentially for the b.status_id and s.status_id; when you join, the column names are taken and the table names basically ignored in terms of what is returned - so something like b.status_id AS b_status_id, s.status_id AS s_status_id would make sure you got the correct values for both of these. You may have done this already of course - it just looked as though you might have not, judging from the column names you gave.
I am not sure if you want to just pick one column from the existing result or issue a query that will get you only what you want. But a better defined query sound the most sensible
SELECT
[ your joins etc ]
WHERE b.firstname = 'Ringo'
AND b.lastname = 'Starr'
Or if you want to just get the Ringo Starr entry from your existing result
foreach ( $resultats as $result ) {
if ( $result['firstname'] == 'Ringo' && $result['lastname'] == 'Starr' ) {
echo 'Got him';
}
}
add WHERE clause with condition that satisfy your needs
alter fields clause leaving only one you need
use fetchColumn() instead of fetchAll()
You're set.
I am currently using the following query to retrieve data from a database:
SELECT product_Id, COUNT(product_Id) as count
FROM my_sales
GROUP BY product_Id
ORDER BY count DESC
in phpmyadmin it looks like this:
_____________________________________
Product_ID | count
__________________|__________________
12 | 13
13 | 21
14 | 24
The PHP Code im using looks like this:
$res = $connVar->prepare($query); //the query described above
$res->execute();
$res->fetch(PDO::FETCH_ASSOC);
while ( $row = $res->fetch(PDO::FETCH_ASSOC) )
{
$data[] = $row;//return the information from the database as an array
echo $data[0]['product_Id']; //trying to target specific indexes of an associative array :/
echo $data[0]['count'];
}
What really needs to happen is that I can store each row as variables so that I can say, print out in php how much stock is left for a particular product.
Been looking on stackoverflow for around 4 hours now and about to give up. There are a lot of questions available about returning the whole dataset within one variable but thats not what i need.
Any help?
I have a database table. It contains the folowing columns:
Cathegory | Priority |
Is there a finished script or a way to display statistics for these columns?
Basically what I am trying to do is show statistics for these columns.
For example,
cathegory can have different values, as an example: (Continent,
Country, City, Street).
Priority can contain a value between 1-10.
So I would need to display how many rows there are, the and the different values for each row.
For example:
4 of the priority 8 rows have 'continent' as catheogry,
43 of the priority 8 rows have 'country' as cathegory,
329 of the priority 8 rows have 'city' as cathegory
Is this possible?
There are no built-in scripts that can do that for you but certainly you get all that kind of information using SQL, that's the basic idea of a relational database.
Number of rows in table
select count(*) from table;
The example
select cathegory, count(cathegory) nbr_of_cathegories_for_prio_8 from table where priority = 8 group by cathegory;
In you example : 329 of the priority 8 rows have 'city' as cathegory
I assume that:
8 - is the priority value.
329 - how many time the priority is repeated for that specific priority for a specific category.
the PHP implimentation will look something like:
<?php
$sql = "
SELECT Priority, COUNT(Priority) as nbr_of_Priorities, cathegory,
FROM table_Name
GROUP BY Priority, cathegory
";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['nbr_of_Priorities'].'of the priority'.$row[' Priority'];
echo 'has'.$row['cathegory'].'as catheogry';
}
?>
position | Average | gpmp
1 70.60 2.0
2 60.20 2.3
3 59.80 4.8
4 59.80 4.8
5 45.70 5.6
Hie All,
As above table, I need to arrange the position according to the lowest gpmp and the highest average. But when the both average and gmp are the same, I will need to have the position to be the same.
For example, position 3 and 4 have the same average and gpmp. How do I generate the mysql query or using php function so that after they detect the same average and gpmp and change the position 4 to 3.
Which mean after the function is generated it will become like the table below.
position | Average | gpmp
1 70.60 2.0
2 60.20 2.3
3 59.80 4.8
3 59.80 4.8
5 45.70 5.6
Here's a simple way to update the table as you described in your post - taking the sequential positions and updating them accordingly. It doesn't calculate the positions or anything, just uses the data already there:
UPDATE `table` t SET position = (
SELECT MIN(position) FROM (SELECT * FROM `table`) t2 WHERE t.Average = t2.Average AND t.gpmp = t2.gpmp
)
I'd give something like the following a try, through it does assume a primary key is on this table. Without a primary key you're going to have issues updating specific rows easily / you'll have a lot of duplicates.
So for this example I'll assume the table is as follows
someTable (
pkID (Primary Key),
position,
Average,
gpm
)
So the following INSERT would do the job I expect
INSERT INTO someTable (
pkID,
position
)
SELECT
someTable.pkID,
calcTable.position
FROM someTable
INNER JOIN (
SELECT
MIN(c.position) AS position,
c.Average,
c.gpm
FROM (
// Calculate the position for each Average/gpm combination
SELECT
#p = #p + 1 AS position,
someTable.Average,
someTable.gpm
FROM (
SELECT #p:=0
) v,someTable
ORDER BY
someTable.Average DESC,
someTable.gpmp ASC
) c
// Now regroup to get 1 position for each combination (the lowest position)
GROUP BY c.Average,c.gpm
) AS calcTable
// And then join this calculated table back onto the original
ON (calcTable.Average,calcTable.gpm) = (someTable.Average,someTable.gpm)
// And rely on the PK IDs clashing to allow update
ON DUPLICATE KEY UPDATE position = VALUES(position)
(pseudo code)
select * from table
get output into php var
foreach (php row of data)
is row equal to previous row?
yes - don't increment row counter, increment duplicate counter
no - increment row counter with # of duplicates and reset duplicate counter
save current row as 'previous row'
next
you can try something like this in php:
$d= mysql_query('select distinct gpmp from tablename order by gpmp');
pos= 1;
while($r= mysql_fetch_array($d)){
mysql_query('update tablename set position='.$pos.' where gpmp='.$r['gpmp']);
$pos++;
}
You only need to "expand" the idea to take averange in account too.
This is the books table on db;
book_ID writer_ID
-------- -----------
1 10
2 10
3 10
4 10
5 10
This is the rates table on the db,
book_ID rate
------- --------
1 4
2 3
2 5
2 1
2 4
3 5
4 2
4 5
4 2
4 4
5 3
now, i have the writer_ID at first, and i have to find all book_ID (connected to that writer_ID) and the average rates of each book_ID from the rates table. finally, i have to find the greatest rate average and its book_ID
this is my code
$query="SELECT * FROM books WHERE seller_id ='$id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
//getaveragerate is the function that returns average of the rates from rates table
$arr = array(ID => $info['book_ID'], average => getaveragerate($info['book_ID']));
}
$greatest_average_and_books_id_number = max($arr); // dont know how to get highest average and its ID together from array
that is my question, sorry but english is not my native language, i am trying my best to explain my problem. sometimes i cant and i just stuck.
thanks for understanding.
Or just let the database do it for you:
SELECT max(fieldname) FROM rates WHERE id='34'
If you are limited as to which functions you can perform (ie using some CRUD class):
SELECT * FROM rates WHERE id='34' ORDER BY id DESC LIMIT 1
You haven't told us what fields from the database will be returned by your query. It also looks like you're filtering (WHERE clause) on key column, which should only return one record. Therefore you can strip out everything you have there and only put:
$greatest_record = 34;
No need for a query at all!
With a little more information on what you're doing and what fields you're expecting:
$query = "SELECT id, rate FROM rates";
$result = mysql_query($query);
$myarray = array();
$greatest_number = 0;
while ($row = mysql_fetch_array($result)) {
myarray[] = $row; // Append the row returned into myarray
if ($row['id'] > $greatest_number) $greatest_number= $row['id'];
}
// Print out all the id's and rates
foreach ($myarray as $row_num => $row) {
print "Row: $row_num - ID: {$row['id']}, Rate: {$row['rate']} <br>";
}
print "Highest ID: $greatest_number";
Note that we maintained what was the greatest number at each row returned from the database, so we didn't have to loop through the $myarray again. Minor optimization that could be a huge optimization if you have tens of thousands of rows or more.
This solution is on the basis that you actually need to use the ID and RATE fields from the database later on, but want to know what the largest ID is now. Anyone, feel free to edit my answer if you think there's a better way of getting the greatest_number from the $myarray after it's generated.
Update:
You're going to need several queries to accomplish your task then.
The first will give you the average rate per book:
SELECT
book_id,
avg(rate) as average_rate
FROM Rates
GROUP BY book_id
The second will give you the max average rate:
SELECT
max(averages.average_rate),
averages.book_id
FROM (
SELECT
book_id,
avg(rate) as average_rate
FROM Rates
GROUP BY book_id
)
as averages
WHERE averages.average_rate = max(averages.average_rate)
This will give you a list of books for a given writer:
SELECT book_id
FROM Books
WHERE writer_id = $some_id
Don't try to do everything in one query. Mixing all those requirements into one query will not work how you want it to, unless you don't mind many very near duplicate rows.
I hope you can use this update to answer the question you have. These SQL queries will give you the information you need, but you'll still need to build your data structures in PHP if you need to use this data some how. I'm sure you can figure out how to do that.