Pulling Last Two Dates PHP/MySQL - php

I have a table in my database which is updated randomly. I'm trying to pull entries by the latest date. This part is simply and I can do it with ease. However, I want to pull the two latest dates.
Example; If my last update was 2015-06-22 and the one before than was 2015-06-12 and the one before then was 2015-06-02. I would want to pull 2015-06-22 and 2015-06-15.
I would use a LIMIT 2, however, there are an unknown amount of items that may have the same date attached.
I haven't tried anything other than the LIMIT 2. After some research, I wasn't able to find anything to reference.
Update
I used SELECT DISTINCT to get the desired results.

SELECT DISTINCT dates FROM table ORDER BY dates DESC LIMIT 2
Will give you the latest 2 dates in the table.

I would have a column set to id, that is auto incremented, and do my query like this:
SELECT * FROM tbl_name ORDER BY `id` DESC LIMIT 2
Crap McAdam you beat me to it!

You can get the latest two dates using LIMIT, like you mentioned:
SELECT latestDates
FROM myTable
ORDER BY dateColumn DESC
LIMIT 2;
And you can join that to your original table to only select rows that occur on those two dates:
SELECT m.*
FROM myTable m
JOIN(
SELECT latestDates
FROM myTable
ORDER BY dateColumn DESC
LIMIT 2) tmp ON tmp.latestDates = m.dateColumn;

Related

Query two tables ORDER BY date

So I have two tables that displays values like a Facebook look-a-like feed. They both have a datetime column named date, but I want them to order them together by date DESC.
I think join is the correct way(?), but not quite sure. Can someone help me out?
Currently I have them in two different queries:
$status1 = "1";
$stmt1 = $link->prepare('
SELECT id
, ident_1
, ident_2
, date
, ident_1_points
, ident_2_points
FROM duel
WHERE active=?
ORDER
BY date
');
$stmt1-> bind_param('s', $status1);
and
$status2 = "OK";
$stmt2 = $link->prepare('SELECT id, ident, pp, date FROM sales WHERE status=? AND team IN (2, 3) ORDER BY date DESC LIMIT 20');
$stmt2->bind_param('s', $status2);
How should I do this?
If you want one continuous list containing data from both tables, and the whole thing ordered by date overall, then you might need a UNION query in a subquery, and then order the outer query, something like this:
SELECT *
FROM
(
SELECT id, ident_1, ident_2, date, ident_1_points, ident_2_points
FROM duel
WHERE active=?
UNION ALL
SELECT id, ident, pp, date, NULL, NULL
FROM sales
WHERE status=?
AND team IN (2, 3)
LIMIT 20
) list
ORDER BY date DESC
The requirement isn't 100% clear to be honest from your description (sample data and expected results always helps when asking SQL questions), but I think this is pretty close to what you need.
JOIN doesn't seem appropriate, unless you want a result set where items from each table are linked to each other by some common field, and you combine them such that you get all the columns side by side, showing the data from one table next to the data which matches from the other table.
If you're unsure, I suggest looking at tutorials / examples / documentation which show what JOIN does, and what UNION does.

How can I get first 5 and last 1 records from table mysql?

I'm working on php small project, here I need first 5 records from beginning of records and last record 1 from end of the table's record. I don't know how to write a single mysqli query.
Any help will be appreciated. Thanks in advance.
SQL tables represent unordered sets. So, there is no such thing as the first five rows or last row -- unless a column explicitly defines the ordering.
Often, a table has some sort of auto-incremented id column, which can be used for this purpose. If so, you can do:
(select t.*
from t
order by id asc
limit 5
) union all
(select t.*
from t
order by id desc
limit 1
);
Notes:
Sometimes, an insert date/time column is the appropriate column to use.
You want to use union all rather than union -- unless you want to incur the overhead of removing duplicate values.
For this formulation, if there are fewer than 6 rows, then you will get a duplicate.
The UNION operator allows this, carefully toying with the ORDER BY and LIMIT clauses :
(SELECT * FROM table ORDER BY field ASC LIMIT 5)
UNION
(SELECT * FROM table ORDER BY field DESC LIMIT 1)

PHP MySQL newest records from multiple tables

I'm trying to select the latest 10 records from multiple tables (ORDER BY date). For example, 8 of the newest records might be in one table and 2 in another (10 rows in total). Is there a way to select those 10 records?
SELECT *
FROM
( SELECT * FROM x
UNION ALL
SELECT * FROM y
) n
ORDER
BY date DESC
LIMIT 10;
You can maybe use:
SELECT column_name(s)
FROM table1
ORDER BY date LIMIT 0,8
UNION ALL
SELECT column_name(s)
FROM table2
ORDER BY date LIMIT 0,2;
SELECT * FROM (
SELECT some_data AS alias1, date_field AS mydate
FROM table1
UNION ALL
SELECT datazzz AS alias1, another_datefield AS mydate
FROM table2
)
ORDER BY mydate DESC LIMIT 10
Syntax might need a little bit of tweaking, but that's the gist of it.
Specifically, you need to select whatever data you want out of each of the tables and then use aliases to make sure they have the same column names (otherwise they can't be returned in the same result set). Then after that you need to order by the common date field.

MySQL grouping by day then display the date from the grouped results

So i have a whole load of votes going into a voting system. I want to display how many votes i have in any one day. But i also want to then, display the amount of votes per day and spit out which day they were voted on, i.e 24k votes on 05/06/12, 27k votes on 06/06/12
SELECT count(*) AS count
FROM results
GROUP BY DAY(datesubmitted), YEAR(datesubmitted), MONTH(datesubmitted)
ORDER BY DAY(datesubmitted) DESC, YEAR(datesubmitted) DESC, MONTH(datesubmitted) DESC
Is my query, i tried to add something like
DAY(FROM_UNIXTIME(datesubmitted)) as order_day
but this just throws a null which i found interesting as i'd expect the query to fail as there aren't any outers.
Why don't you simply GROUP BY datesubmitted DESC? Also, no need to ORDER BY if it's following the same criteria as GROUP BY.
Number of votes on a specific day:
SELECT COUNT(*) AS total
FROM results
WHERE datesubmitted BETWEEN #dateMin AND #dateMax
Number of votes for each separate day:
SELECT COUNT(*) AS total, DATE(datesubmitted) AS day
FROM results
GROUP BY DATE(datesubmitted)
ORDER BY DATE(datesubmitted) DESC
UPDATED AGAIN
So just saw a new answer but for me how i got it working was:
SELECT count(*) AS count, DAY(datesubmitted) AS newday,
YEAR(datesubmitted) as newyear ,MONTH(datesubmitted) as newmonth
FROM results
GROUP BY DAY(datesubmitted), YEAR(datesubmitted), MONTH(datesubmitted)
ORDER BY YEAR(datesubmitted) DESC, MONTH(datesubmitted) DESC, DAY(datesubmitted) DESC
This way i get the correct ordering with year, month and day properly and also it displays the dates. I could concat them, but thats for another day.

How to structure this SQL query?

So basically I'm getting notifications of new content on my website. I have 4 tables -
articles
media
updates
comments
Each table has a set of its own columns (I can include these if anyone wants). There is one distinct column every table has, this is the timestamp column (a big int formatted column with data from the PHP time() function). My solution to getting the last 30 modifications is to select the first 30 rows from these 4 tables ordered by timestamp descending.
Here is the query I have so far, it doesn't work and I'm wondering if someone could help me. -
SELECT * FROM `articles`
UNION SELECT * FROM `media`
UNION SELECT * FROM `updates`
UNION SELECT * FROM `comments`
ORDER BY `timestamp` DESC
LIMIT 30
EDIT:
I was also using another query before -
SELECT * FROM `articles` ,`media` ,`updates` ,`comments`
ORDER BY `timestamp` DESC
LIMIT 30
and kept getting this error -
Column 'timestamp' in order clause is ambiguous
EDIT 2
I realise now I have to use the AS clause in my statement to combine these results into one table.
SELECT a.*,m.*,u.*,c.* from articles AS a
LEFT JOIN media AS m ON (m.timestamp = a.timestamp)
LEFT JOIN updates AS u ON (u.timestamp = a.timestamp)
LEFT JOIN comments AS c ON (c.timestamp = a.timestamp)
ORDER BY timestamp desc LIMIT 30
Your union can work, but only if you can create some sort of common field list. For example, lets say you have a description field in each table, with different names. Something like this will work...
SELECT TimeStamp,'Articles',Art_desc AS Description FROM articles
UNION ALL
SELECT TimeStamp,'Media',Media_Desc FROM Media
UNION ALL
SELECT TimeStamp,'Updates',Update_Desc FROM Updates
UNION ALL
SELECT TimeStamp,'Comments',Comment FROM Comments
ORDER BY timeStamp DESC LIMIT 30
In essence, you are creating result sets of 3 consistent columns, so UNION will work in this case.

Categories