count all items in table mysql plus get record - php

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 :)

Related

issue with mysql query and optimization into one query

I have a query that determine a users rank based on their actions
$db->row("SELECT COUNT(ID) as `user_rank` FROM userdetails WHERE (userdetails.totalaction /4) >= ('$user_detailed->totalaction' /4) AND active = 1 AND frozen = 0",array());
The above will return there rank and I want to make one query to update all users at once.
Basically I want the >= ('$user_detailed->totalaction' /4) to become pure sql no php in the query
so if i had 100 users it will work out each of there ranks and update another field called current_rank is it possible to do this all in one query if so can someone help me out.
You simply need to replace ('$user_detailed->totalaction' /4) with your desired value to test against. For example if you want it greater than equal 10, then it should be:
$db->row("SELECT COUNT(ID) as `user_rank` FROM userdetails WHERE (userdetails.totalaction /4) >= 10 AND active = 1 AND frozen = 0",array());
figured out how to do it had to do two queries not one like i wanted ;) thanks for help

MYSQL count rows instead of showing results

So I have the following query, which I use it to get some analytics stats.
SELECT count(*) as total,CONCAT(YEAR(created),'-',MONTH(created),'-',DAY(created))
as date_only FROM logs where action = 'banner view'
and created BETWEEN '2015-07-03 21:03'
AND '2017-08-02 21:03' group by date_only order by created asc
This works, and it gives me this:
So what I actually need is, the total count of the rows in this case is 20, this is a dummy example, but I need to use this count to check before showing the stats if the data is too big to be displayed on a graphic.
Can this be achieved?
//LE
So the process will be like this:
1. Get a count of the total rows, if the count of rows is smaller than X(number will be in config and it will be a basic if statement), then go ahread and run the above query.
More info:
I actually use this query to display the stats, I just need to adapt it in order to show the total count rows
So the result of thquery should be
total | 20 in this case
I think you would want to use a derived table. Just wrap your original query in parenthesis after the FROM and then give the derived table an alias (in this case tmp). Like so:
SELECT count(*) FROM (
SELECT count(*) as total,CONCAT(YEAR(created),'-',MONTH(created),'-',DAY(created))
as date_only FROM logs where action = 'banner view'
and created BETWEEN '2015-07-03 21:03'
AND '2017-08-02 21:03' group by date_only order by created asc
) as tmp;
If I understand what you want to do correctly, this should work. It should return the actual number of results from your original query.
What's happening is that the results of the parenthesized query are getting used as a sort of virtual table to query against. The parenthesized query returns 20 rows, so the "virtual" table has 20 rows. The outer count(*) just counts how many rows there are in that virtual table.
Based on the PHP tag, I assume you are using PHP to send the queries to MySQL. If so, you can use mysqli_num_rows to get the answer.
If your query result is in $result then:
$total = mysqli_num_rows($result);
Slightly different syntax for Object Oriented style instead of procedural style.
The best part is you don't need an extra query. You perform the original query and get mysqli_num_rows as an extra without running another query. So you can figure out pagination or font size or whatever and then display without doing the query again.
This is an small query but works fine, and give me the total number of rows, you just need add your conditions.
SELECT COUNT(*) FROM table WHERE field LIKE '%condition%'
The group by I think you need to eliminated, becouse, this instead of count the records, divide in all your group by, example: records = 4, with group by you have
1
1
1
1
I hope this help you
You can try this way .
SELECT COUNT(*) FROM ( SELECT count(*) as total,CONCAT(YEAR(created),'-',MONTH(created),'-',DAY(created))
as date_only FROM logs where action = 'banner view'
and created BETWEEN '2015-07-03 21:03'
AND '2017-08-02 21:03' group by date_only HAVING total >=20 ) temp

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

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...

php / mysql - how to get rankings of users?

for example i have a table like this :
name rating
matei 124
andrei 20
serj 25
john 190
mike 96
andy 245
tom 73
i need to output something like this(order by rating):
john's position is 2; or, tom's position is 5; (i don't need to get all result , just one )
How can I achieve this?
Thanks in advance
Generally order of rows in a query result is not guaranteed by MySQL unless ordering is explicitly specified with ORDER BY clause. If you have some separate ordering column, you may use query like the following:
SELECT count(1) as position
FROM table
WHERE order_column <= {john's order_column value};
If you don't have ordering column, I'd recommend you to define first, what does "john's position" and "tom's position" mean.
UPDATE:
AFAIU, you want to get position in list sorted by rating (sorry, I initially did not get it). So, rating would be your order_column. In this case, you should decide, how do you calculate position, if two guys have equal rating (who's position is higher?).
So, the query may look in the following way:
SELECT count(1) as position
FROM table
WHERE
rating > (SELECT rating FROM table WHERE id={user's ID});
SELECT COUNT(*) + 1
FROM users
WHERE (rating, name) <
(
SELECT rating, name
FROM users
WHERE name = 'john'
)
Note that if you will have duplicates on both name and rating, this query will assign the same rating to both of them.
Tables are more formally known as relations in database literature - they are not guaranteed to be ordered (they are sets of "tuples"), so your question doesn't make sense. If you need to rely on an order/position, you need to define an additional column (like an auto-incrementing ID column) to capture and store that info.
Is this any help > http://craftycodeblog.com/2010/09/13/rownum-simulation-with-mysql/ ?
Would offset not work like so?
SELECT * FROM Table ORDER BY rating DESC LIMIT 1,6
This would return 1 row that has been off setted by 6 rows ? or am I mistaken, the syntax would be
SELECT * FROM Table ORDER BY rating DESC LIMIT 1 , {{POS}}

Categories