MYSQL count rows instead of showing results - php

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

Related

MySQL Query showing only the last item grouped by user

I got a database that registers user actions and their geolocation.
Now I would like to fetch this data at the hand of the last action per user.
The table looks a bit like:
geoaction_id AUTO INCREMENT
geoaction_user
geoaction_creationdate (Y-m-d H:i:s)
geoaction_action
geoaction_lon
geoaction_lat
Now I would like to make a simple query that selects of all users the last item.
But LIMIT 0,1 just parses one row no matter what. (LOGICALLY!!)
Group by gives a little better result.
But how to get only the last item per user?
Try this, please provide the queries you have checked out so far, in order to assist you better.
SELECT geoaction_user, geoaction_action
FROM table-name
GROUP BY geoaction_user
ORDER BY geoaction_action DESC LIMIT 1
Working with sets:
SELECT
g.geoaction_user,
g.geoaction_action,
g.geoaction_creationdate,
g.geoaction_lat,
g.geoaction_lon
FROM
(
SELECT
geoaction_user,
MAX(geoaction_id) max_id
FROM
geoactions
GROUP BY geoaction_user
) s
JOIN
geoactions g
ON s.geoaction_user = g.geoaction_user
AND s.max_id = geoaction_id
The subquery generates a virtual table with the geoaction_id from the latest entry in the tabble for each user_id, then the table is joined to get the data belong to the latest id.
If you need to filter out some records place the where clause in the subquery

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

Counting The Total Records From Table in Pagination Mode

I have a project with a table (figure A) and display all the records to the web browser with pagination something like this:
How can I do so that the cumulative each page of the 'Amount' counted correctly in the last page?
I've try by looping but it give me result in page 1 = 21, page 2 = 24, and so on. Of course this is wrong.
Need help. Thank You
Make a separate query for the total amount:
SELECT SUM(Amount) AS TotalAmount
FROM tablename
Then display it in the end of the pages, outside of the loop.
Well MySQL WITH ROLLUP is used for this. This adds an extra row at last and can be used with aggregate functions.
SELECT
id,
IFNULL(stock,'Total') AS `stock`,
SUM(amount) AS Total
FROM board
GROUP BY stock WITH ROLLUP
You can add limit in this query according to your requirements
SQL Fiddle Example
With Limit
SQL Fiddle Example

I need to select newest rows from a MySQL database, but verify that I am also returning a row with a given ID

I'm new to this, sorry if the title is confusing. I am building a simple php/mysql gallery of sorts. It will show the newest 25 entries when a user first goes to it, and also allows off-site linking to individual items in the list. If the URL contains an ID, javascript will scroll to it. But if there are 25+ entries, it's possible that my query will fetch the newest results, but omit an older entry that happens to be in the URL as an ID.
That means I need to do something like this...
SELECT * FROM `submissions` WHERE uid='$sid'
But after that has successfully found the submission with the special ID, also do
SELECT * FROM `submissions` ORDER BY `id` DESC LIMIT 0, 25`
So that I can populate the rest of the gallery.
I could query that database twice, but I am assuming there's some nifty way to avoid that. MySQL is also ordering everything (based on newest, views, and other vars) and using two queries would break that.
You could limit across a UNION like this:
(SELECT * FROM submissions WHERE uid = '$uid')
UNION
(SELECT * FROM submissions WHERE uid <> '$uid' ORDER BY `id` LIMIT 25)
LIMIT 25
Note LIMIT is listed twice as in the case that the first query returns a result, we would have 26 results in the union set. This will also place the "searched for" item first in the returned sort result set (with the other 24 results displayed in sort order). If this is not desirable, you could place an ORDER BY across the union, but your searched for result would be truncated if it happened to be the 26th record.
If you need 25 rows with all of them being sorted, my guess is that you would need to do the two query approach (limiting second query to either 24 or 25 records depending on whether the first query matched), and then simply insert the uid-matched result into the sorted records in the appropriate place before display.
I think the better solution is:
SELECT *
FROM `submissions`
order by (case when usid = $sid then 0 else 1 end),
id desc
limit 25
I don't think the union is guaranteed to return results in the order of the union (there is no guarantee in the standard or in other databases).

Check if data exists across multiple tables

I am currently running this query inside MySQL to check if the specified values exists
within the table associated with them.
SELECT COUNT(artist.artist_id), COUNT(album.album_id), COUNT(tracks.track_id)
FROM artist, album, tracks WHERE artist.artist_id = 320295 OR album.album_id = 1234 OR tracks.track_id = 809
The result I get from running this query is all 1, meaning that all the statements after the WHERE clause is true. To further check the query's reliability, I changed the tracks.track_ = 809 to 802, which I know does not match. However the results displayed are still all 1, meaning that they were all successfully matched even when I purposefully inserted a value which would not have matched.
How do I get it to show 1 for a match and 0 for no matches within the same query?
EDIT: I have inserted an image of the query running
What you do here is a join over three tables. You can see what happens, when you look at this SQL Fiddle.
In the first select, I have left out the count, to show how the join works. You can also see how the result set changes, when you modify the where clause from or to and as #RayPaseur suggested.
I guess, what you want, is really three separate queries
select 'artist' as type, count(artist_id) as count
from artist
where artist_id = 320295
union
select 'album', count(album_id)
from album
where album_id = 1234
union
select 'track', count(track_id)
from tracks
where track_id = 809
which becomes
TYPE COUNT
artist 1
album 1
track 1
Now, when you change track_id = 809 to track_id = 802, you will get
TYPE COUNT
artist 1
album 1
track 0
as a result.
SQL Fiddle for playing.
The "or" clause may be your issue here. If any of those WHERE clauses works, you will have a results set that is not empty. Maybe something like SELECT COUNT(*)... WHERE... AND... AND...
But it would be more helpful to see the entire PHP code set. And I would recommend running three different queries - not because it's technologically sophisticated, but just because it is easier to get it to work right the first time!

Categories