SQL Query matching two fields - php

I currently have a table called cc_site, in this table I store the results of pings from different ip addresses.
The table has four fields:
auto increment ID field
date (which includes time)
IP address
status (used to determine if the ping was successful or not).
I'm trying to create a query which will give me the latest result based off the date field for an individual ip address. The code I'm currently using is below but it doesn't work unless the IP I'm using in the query is the latest entry in the table.
$query = "SELECT *
FROM cc_site
WHERE ip='$host'
AND Date IN (
SELECT max(date)
FROM cc_site
)";
I knew the query is incorrect however I have not been able to find code that would perform the query I need.
Any help would be great.

No need of that sub-query. Use can use ORDER and LIMIT instead -
SELECT * FROM cc_site WHERE ip='$host' ORDER BY `date` DESC LIMIT 1
This will sort the records in descending order according to date and return the record with highest record.

select * from cc_site
where ip='$host' and date in(select max(date) from cc_site where ip='$host');
I think this might give you the answer

Related

Pulling data from MySQL database and pulling only 1 value of each in a column and then show latest first

What I'm trying to do.
To pull data from a database. With one column 'serial_no' to only pull 1 of each value so it's unique, and any other values within the 'serial_no" column to not show if another one of the same value exists. So in column 'serial_no' there could be 35k values but it would only show 35 if there are a total of 35 unique serial numbers. Once I have them I need them to show the latest first by 'datetime' column.
Current outcome.
I have the data pulling through, and it's only showing once of each 'serial_no' however, it's not showing the latest first, like it seems to be ignoring the ordering or just pulling through the first one it sees rather than the latest.
These 2 PHP queries I have used and working but not 100% how it should. The first one, i only want 'serial_no" distinct not all columns, so maybe that's why this one is not working.
$sql = "SELECT DISTINCT serial_no, datetime FROM wp_clicker_data ORDER BY datetime DESC";
The other one which works fine apart from it does not show the latest value of a specific serial_no
$sql = "SELECT * FROM wp_clicker_data GROUP BY serial_no ORDER BY datetime DESC";
Any ideas how each unique value of column 'serial_no' can pull through the latest entry based on the latest 'datetime' column?
Thanks!
Use Max and GROUP BY to get your desired output as below-
SELECT serial_no,
MAX(datetime)
FROM wp_clicker_data
GROUP BY serial_no
If you want the latest row for each serial number, then use filtering:
select cd.*
from wp_clicker_data cd
where cd.datetime = (SELECT MAX(cd2.datetime)
FROM wp_clicker_data cd2
WHERE cd2.serial_no = cd.serial_no
);
GROUP BY is not appropriate when you want to retrieve entire rows. Using SELECT * with GROUP BY doesn't make sense, because there are columns in the SELECT that are not in the GROUP BY. And this construct generally won't work (with the default settings) in the more recent versions of MySQL.

Selecting multiple tables and displaying them ordered by datetime column

I want to display the logs to recent activities page ordered by date. Now I was trying to execute this to my mysql
"SELECT * FROM tracking_log.editlog, tracking_log.deletelog, tracking_log.loginlog, tracking_log.logoutlog ORDER BY time ASC";
but it always says
Column 'time' in order clause is ambiguous
all of the tables have a time column, format by datetime (0000-00-00 00:00:00)
How am I going to fetch them ordered by time?
Thanks in advance!
By which table's time column you want to order?
Assuming you want to order the result set by tracking_log.editlog.time column then the query would look like below:
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY tracking_log.editlog.time ASC;
Just in case if all of the time columns in the respective table don't contain NOT NULL values at the same time then you need to use COALESCE I guess.
Query using COALESCE
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY
COALESCE(tracking_log.editlog.time , tracking_log.deletelog.time, tracking_log.loginlog.time,tracking_log.logoutlog.time) ASC;
'tracking_log' is your database name, and you're selecting multiple tables from that database, so you need to specify from which table you want to order 'time' by:
select * from tracking_log.editlog, tracking_log.deletelog ORDER BY tracking_log.editlog.time ASC
or whichever table from your database you want to use 'time' from. This will fix the error but won't return any results because you have multiple tables in a SELECT clause without anything relating them together.
You'll need to specify some common columns on which you want to return results rather than getting the wildcard and then UNION the tables to aggregate the results. For example, if you have common columns userID, description and time in all your tables, you could do the following:
(SELECT userID, description, time FROM tracking_log.editlog)
UNION
(SELECT userID, description, time FROM tracking_log.deletelog)
ORDER BY time

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

In PHP, how do I ask a mySQL database to retrieve multiple most recent records that match a certain value?

I have a table that has the following fields:
candy_name
candy_type
candy_amount
candy_vendor
One candy_type can have multiple candy_names, like "gummis" might have "orange," "watermelon," "sour watermelon," and so on.
What I am doing is searching this table by vendor, and then I want to see the most recent entry for each unique candy_type (ignoring candy_name). That is, the most recently added row for each unique candy_type.
So I found out how to do the part about finding all the unique candy_types in that table:
$sql = "SELECT DISTINCT candy_type FROM candy_table
WHERE candy_vendor LIKE '%$user_searchbox_input%'
ORDER BY candy_vendor ASC";
$result=mysql_query($sql);
Now I need to find out how to retrieve the MOST RECENT record for each unique candy_type.
Like for the candy_type of "gummi," if the last record matching that type was "orange," that's the one I want to see---not the others.
And for the candy_type of "chocolate," if the last matching record was "milk," I don't care about the others, but I want to retrieve that most recent record matching that candy_type.
How do I do that?
If you want the most recent, use a having clause, combined with a group by, because the group by already selects distinct columns, you can drop the distinct clause.
$user_searchbox_input = mysql_real_escape_string($user_searchbox_input);
$sql = "SELECT candy_type FROM candy_table
WHERE candy_vendor LIKE '%$user_searchbox_input%'
GROUP BY candy_vendor
HAVING timeadded = MAX(timeadded)
ORDER BY candy_vendor ASC";
$result=mysql_query($sql);
See: http://www.techonthenet.com/sql/having.php
Unfortunately, from those four columns there's no way of telling which record is the most recent.
I would suggest adding a date_time column via the ALTER TABLE command. You can refer to http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for syntax help if you need it.
This won't help you with your current query, but it will help for any future queries.
Sort your data by create_date (ORDER BY) or whatever your create timestamp is and then do SELECT * FROM tbl LIMIT 1; # Retrieve first row

finding the number of 1's in my table in order

I have a table of customers with a 1 recorded against their customerid on different dates.
I would like to find the sum of the 1's recorded in descending order. I'm using MySQL and php
Thanks
My guess is that you want the sum of records marked with 1 per customer and sort that result in descending order? If so, the following should do the trick :
select cust.id, sum(cone.one) as number_ones
from customers as cust
inner join customer_ones as cone on cone.id=cust.id
group by cust.id
order by number_ones desc
This is assuming that 'one' is the column containing ones (and only contains 0 or 1 - otherwise you will have to add WHERE cone.one = 1), customers is your customer table and customer_ones is the table containing your customer data.
As i get you right, this is simple sql request what u need:
SELECT COUNT(id) as total from customers
Just make in php:
$sql="SELECT COUNT(id) from customers";
$query=mysql_query($sql) or die(mysql_error());
$res=mysql_fetch_assoc($query);
$summ=$res['total']; //<- Your summ (i.e. quantity of rows in table)
Btw, you can use mysql_num_rows instead.
Or explain please more accurately what output you need. To make sorting by date or any other dependency you will need to make other request using WHERE clause and date comparison.

Categories