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';
}
?>
Related
I want to select different MAX(values) of different sensornodes. My Problem is that the WHERE...IN... clause works like many logical "OR", but I need the MAX($measure) from each sensornode. I know how to do it with a loop, but I think there is a better solution to do this.
This is the table 'measurement' of the database:
ID humidity temperature date time sensornode
---------- ---------- ----------- ---------- ---------- ----------
1 22.00% 18.00C 06/03/2017 13:07:18 WSN1
2 22.00% 18.00C 06/03/2017 13:08:19 WSN2
3 34.00% 21.00C 06/03/2017 13:09:19 WSN3
4 21.00% 20.00C 06/03/2017 13:10:19 WSN4
The query should be somthing like this
$measure //is either 'temperature' or 'humidity', depends on the users input.
$sensornode // is a string which is converted with the implode-function from an array which includes the selected 'sensornodes' of the users input
$sql_query = "SELECT MAX($measure) AS $measure
FROM measurement
WHERE sensornode IN ('$sensornode')";
$data = executeQuery($sql_query, $measure);
To get the maximum value for each sensor node, use grouping:
SELECT sensornode,
max(temperature)
FROM measurement
GROUP BY sensornode;
To restrict that to certain sensor nodes, just add a WHERE:
SELECT sensornode,
max(temperature)
FROM measurement
WHERE sensornode IN ('WSN1', 'WSN2', ...)
GROUP BY sensornode;
I have a table that I have fed data into through a PHP script, and am managing it using phpMyAdmin. My table has 4 columns. The first is an auto increment, second and third are values being fed in, and the final is meant to keep track of how many times the value from column 3 has appeared.
This is how my table currently appears
RowNumber UserID SongID Plays
1 540 2191 0
2 540 2671 0
3 550 3891 0
4 550 2191 0
5 550 2671 0
6 560 9391 0
7 560 2191 0
I want to search through the whole table and change the value in the Plays column to show how many times the value appears in the table.
Ideally, this is how I want my table to output:
RowNumber UserID SongID Plays
1 540 2191 3
2 540 2671 2
3 550 3891 1
4 550 2191 3
5 550 2671 2
6 560 9391 1
7 560 2191 3
Is there a way to search through the table and update these values?
The amount of data being inputted into the table is quite large, so an efficient solution would be greatly appreciated.
Consider using a view instead of a table, unless you need the value cached for performance reasons. You can compute the count of each value in a subquery and join the results back to the table like so:
SELECT Table.RowNumber, Table.UserID, Table.SongID, x.Plays
FROM Table
INNER JOIN (
SELECT SongID, COUNT(*) AS Plays
FROM Table
GROUP BY SongID
) x
ON Table.SongID = x.SongID;
And create a view from it using CREATE VIEW TableWithPlays AS SELECT .... Having an index on SongID will allow the subquery to complete rather quickly, and you will never have to worry about the Plays column being up to date.
If you do in fact want to cache the values, use an UPDATE query based on the above query:
UPDATE Table a
INNER JOIN (
SELECT SongID, COUNT(*) AS Plays
FROM Table
GROUP BY SongID
) b
ON a.SongID = b.SongID
SET Plays = b.Plays;
As with the view solution, don't forget the index on SongID.
I think you can use simple PHP query that is run periodically (Note: not an actual code):
$sql = "SELECT UserID, SongID, COUNT(RowNumber) AS CNT FROM SomeTable GROUP BY 1, 2 ORDER BY 3 ASC";
foreach($result as $row){
$sql = "UPDATE SomeTable SET Plays = ".$row['CNT']." WHERE UserID = '" . $row['UserID'] . "' AND SongID = '" . $row['SongID'] . "'";
}
I have a table that looks like this
id | itemID | catID | Title
----------------------------------------------------------------------------
0 3 4 Hello
1 3 6 Hello
2 4 4 Yo
3 4 8 Yo
4 5 2 Hi
5 1 3 What
I want to do a MySQL PHP Select that only gets one occurrence of the itemID. As you can see they are the same item, just in different categories.
This is what I tried
SELECT * FROM Table GROUP BY itemID
That didn't seem to work, it still just shows duplicates.
Is this what you are looking for? http://www.sqlfiddle.com/#!2/5ba87/1
select itemID, Title from test group by itemID;
As far as MySQL is concerned, the data is all unique, since you want all of the columns. You have to be more specific.
Do you just want the itemID (or other column)? Then say so:
select [column] from Table GROUP BY itemID
Do you want the last entry of a particular item ID? Then say that:
select * from Table where itemID = 1 ORDER BY id DESC
Or the first one?
select * from Table where itemID = 1 ORDER BY id
If none of these are what you want, then you probably need to restructure your tables. It looks like you want different categories for your items. If so, then you'll want to split them out into a new join table, because you have a many-to-many relationship between Items and Categories. I recommend reading up on database normalization, so you're not duplicating data (such as you are with the titles).
If you want everything for the distinct itemIDs, you could certainly take a long route by doing one selection of all of the distinct itemIDs, then doing a series of selections based on the first query's results.
select distinct(`itemID`) from Table
Then in your PHP code, do something like this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$itemID = $row['itemID'];
$sql2 ="SELECT * FROM Table WHERE 1 and `itemID`=\"$itemID\" limit 1";
$result2 = #mysql_query($sql2, $connection);
while ($row2 = mysql_fetch_array($result2))
{
$id = $row2['id'];
$itemID = $row2['itemID'];
$catID = $row2['catID'];
$Title = $row2['Title'];
}
}
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'];
// ...
}
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.