How to use 2 MySQL SELECT Statements in one PHP query - php

Please help me figure out how to put the following two statements into one query. Your help is much appreciated.
$sql1 = 'SELECT COUNT(id) as total_cat_votes FROM votes WHERE category_id="1"';
$sql2 = 'SELECT COUNT(nominee_id') as total_nom_votes FROM votes WHERE category_id="1" AND nominee_id="16"';
My Idea here is I have a table called votes and I want to get the number of total votes for a specific category under category_id as well as the different total votes of each nominee under nominee_id. I hope I am clear enough.
Thanks for the help!

Use SUM() for the second count with a condition, using sum with a condition will result in a boolean as 0 or 1,also using aggregate functions without grouping them will result in a single row
SELECT COUNT(id) as total_cat_votes,
SUM(nominee_id='16') as total_nom_votes
FROM votes
WHERE category_id='1'

Related

Php Mysql sum total with select all rows returned

How can i query and return all the rows but with "SUM" added to my query?
Here is my sample query:
select SUM(amount) as total, user_id, username, from table where user_cat = '1';
if I remove SUM, I get the correct number of rows returned, but when I add SUM, the row result is decreased.
Any Idea how to do this?
You have noticed it's impossible to make the query in the way you tried as SUM() aggregates the other rows and only one row is displayed. One way to solve this is to separate SUM() in a subquery as described below:
select n.total,
user_id,
username
from table,
(select SUM(amount) as total
from table
where user_cat = '1') n
where user_cat = '1';
I prefer to make this in two separate queries. Now you'll have to deal with the first column and make it invisible. If you use two queries you'll have to deal with the second query. The choice is yours.

count all items in table mysql plus get record

Hi I have this situation:
$query = $db->query('SELECT COUNT(*),* FROM memberFileReports');
$data = $query->fetch(PDO::FETCH_ASSOC);
print_r($data);
its not working ? any idea why and how to Count and get all items at the same time, and what if I want to Count (*) and then next Select will have Limit 0,5?
Is this what you're looking for?
SELECT * , CONCAT('', (SELECT COUNT(*) FROM memberFileReports)) AS total
FROM memberFileReports LIMIT 0,5
EDIT 1: Note that the 'total' will be a string
EDIT 2: As I understand , you want to get the total rows in the table, but only select 5 of them (as example)
EDIT 3: caps... and misspell
Use this
SELECT * , COUNT(*) FROM memberFileReports Group by column_id
Instead of this
SELECT COUNT(*),* FROM memberFileReports
EDIT:
try this
$data = $query->fetchAll();
instead of
$data = $query->fetch(PDO::FETCH_ASSOC);
I know this post is a little late but i figured i would tell you, the reason why you only get one row back is because you are using an aggregate function "COUNT()". that function makes it so the result is returned in one row. the way to show stuff in more than one row is to use a "GROUP BY" in your select statement and it will group the data by the condition you tell it to.
example... suppose we had an example table with 3 users..
one has 10 interactions
one 3
and one 33:
SELECT
e.UserID,
COUNT(e.interactions) as num_interactions
FROM example e
GROUP BY e.UserID;
that would show the number of interactions a user has made in the dummy example table.
OUTPUT:
UserID num_interactions
1 3
2 10
3 33
without the GROUP BY the aggregate would make the output look like this:
UserID num_interactions
1 46
just for future reference :)

PHP MYSQL - Count & Average In Same Query

This may be very simple but I am trying to do a query that will return the average of the results but I also want it to count the number of rows it used to get the average. For example:
Row 1 = 5
Row 2 = 2
Row 3 = 9
Row 4 = 1
Average = 4.25
Count = 4
Is there a way to do this with one query apposed to two. When i used the avg function is always just returns one row so my count is 1 instead of 4. I need a query that will average but also tell me how many records it went through.
I am trying to avoid using two queries. Thank you for your help.
This is pretty basic and should have been discoverable via search.
SELECT COUNT(field) as `count`, AVG(field) as `average` FROM table_name
In the terms you have stated - if you aren't GROUPing or things like that - you'd just write
SELECT COUNT(col) AS cnt, AVG(col) AS avg FROM tbl;
and you ought to have no problems. You get one row, with the fields cnt and col containing what you need.
The problem you're having is probably due to the use of mysql_num_rows to get the count, which is not correct.
forgot to add: or to the fact that you did not supplied your whole problem.
You can use multiple aggregate functions in a single query:
SELECT COUNT(*), AVG(field) FROM mytable
SELECT COUNT(*), AVG(YourColumn)
FROM YourTable

Get total number of rows meeting WHERE condition

I'm making a search application, and I want to figure out how many results a certain query fetches in order to calculate how many pages of results there are. I basically have:
mysql_query("SELECT * FROM table WHERE conditions LIMIT $page*$items, $items");
Do I have to do a query w/o the limit clause to get the total number, or is there a better way? Thanks!
SELECT COUNT (*) FROM table WHERE conditions
SELECT COUNT(*)
FROM table
WHERE conditions
I see you're using PHP. Once you've run the query, why don't you mysql_num_rows in PHP? That way you won't need to run two queries.
$page_count=10 // no of rows per page
$record=mysql_query("select count(*) from table where conditions");
$row=mysql_fetch_row[0];
$no_of_pages = ceil($row/$page_count);

Apply a limit of 10 after taking distinct records in mysql

In a MySQL table, I would like to take 10 records with DISTINCT values.
I am using Zend Framework.
$select = $this->getAdapter()->select()
->from('table', 'column')->group('column')
->limit(10, 0);
This is the query generated by the above code.
SELECT table.column FROM
table GROUP BY column LIMIT 10
What happens here is that MySQL is taking 10 records first and then applying the group by. So finally, I am getting only 7 records.
How to apply DISTINCT first and then take 10 records from it?
Test that SQL against a table -- MySQL applies the limit last, so doesn't do what you're saying. eg test against
a0 a1
1 1
2 1
3 2
4 2
and do select A.a1 from A group by a1 limit 2. You should see 1, 2, not 1, 1.
[I wanted to say this as a 'comment' rather than an 'answer', but couldn't]
I'm not 100% sure what you are trying to do.
But if i am reading it correct you need 10 records with a certain criteria and then apply the group. not the other way around.
Can't you use WHERE in this case?
SELECT table.column FROM table WHERE "criteria" GROUP BY column LIMIT 10
Regards
Mike
This may help you (I didn't test it but so I'm not sure it's working)
SELECT DISTINCT column FROM table LIMIT 10
If it's not working, you may use a temporary table (like (SELECT column FROM table) TEMP), which will select the distinct elements, then a query which will select the first ten results into this table.
Hope this'll help :)
In ZF, You should use distinct() method into Your query chain :
$select = $this->getAdapter()->select()
->distinct()
->from('table', 'column')
->limit(10, 0);
SELECT DISTINCT column
FROM table
LIMIT 10
GROUP BY column
Not sure how to get it into classes though...

Categories