I have a table like this
my table is here
I need to fetch the table such that the valid_from date is less than the the date which I have(date cannot be current date).
For example. If my date is 02-04-2015, I should get the row with id 120.
Plz help me to do this in php
Please try below quewry :
$input_date = "02-04-2015";
$your_date = date("Y-m-d",strtotime($input_date));
$sql = "SELECT * FROM `table_name` where DATE(validFrom) < '".$your_date."'";
as per your example
SELECT * FROM `your_table_name` where validFrom < '02-04-2015' order by validFrom desc LIMIT 1
or
SELECT * FROM `your_table_name` where validFrom < '02-04-2015' order by validFrom asc LIMIT 1
set order by as per your expectation of output
here you want to pass date as per your date format
Related
I use MariaDB and have a table where each row has a date and a score.
I want to first show the rows where the date is 3 days old or newer, sorted by the score - then show the rest (more than 3 days old) sorted by date.
Since my date is stored in unix time, it's fairly easy to have php calculate 3 days from before now and use that as my $scoreTimeLimit variable in the below:
Here are my two queries:
SELECT * FROM myTable WHERE myDate > $scoreTimeLimit ORDER BY myPopularityScore DESC
SELECT * FROM myTable WHERE myDate < $scoreTimeLimit ORDER BY myDate DESC
However, I would VERY much like to have only 1 query instead of two. Can it be done...?
This is a job for UNION.
SELECT * FROM (
SELECT 0 ord1, NOW() as ord2, *
FROM myTable WHERE myDate > NOW() - INTERVAL 3 DAY
UNION ALL
SELECT 1 ord1, myDate as ord2, *
FROM myTable WHERE myDate <= NOW() - INTERVAL 3 DAY
) a
ORDER BY ord1, ord2 DESC, myPopularityScore
The inner query gives you a single result set with a couple of extra columns added on to help you manage your sorting.
I want to check if the user has 5 records in my MySQL database in the last hour. That´s how I am doing it now:
$link = mysqli_query($link, "SELECT * FROM find_points WHERE timestamp > '.time()-3600.' AND user_id = '1' ORDER BY id DESC");
if(mysqli_num_rows($link) >= 5) {
echo 'more than 5 results';
}
It looks like it should work, but it doesn't work...
Please use below query
SELECT * FROM find_points WHERE TIMESTAMPDIFF( hour, timestamp , now() ) > 1 AND user_id = '1' ORDER BY id DESC
You can read in manual about TimestampDiff
It can be used to run difference between 2 dates in various formats.
Please check the Demo on SqlFiddle
It shows how TimestampDiff returns result and you can use the same in WHERE clause.
Update
Based on your comment, that the timestamp is stored as Unix Timestamp, you could use the following query:
SELECT * FROM find_points WHERE TIMESTAMPDIFF( hour, FROM_UNIXTIME(timestamp) , now() ) > 1 AND user_id = '1' ORDER BY id DESC
FROM_UNIXTIME will convert your UNIX Timestamp to DateTime Format. You can then pass this to TIMESTAMPDIFF which will calculate difference and return the number of hours.
Hope this helps.
"SELECT * FROM find_points WHERE timestamp > DATE_ADD(NOW(), INTERVAL 1 HOUR) AND user_id = '1' ORDER BY id DESC"
I need to get the data based on year with pagination,if the rows count is less,then search in next year
SELECT *
FROM `user_notifications`
WHERE DATE_FORMAT(created_at, '%Y') = '2019'
ORDER BY `created_at` DESC
LIMIT 0,10
if rows count is less than 10,then search by year 2018
Given that your results are sorted by created_at DESC, I don't think a WHERE clause is necessary at all. If there are insufficient results from 2019, your query will automatically return results from 2018, 2017, 2016 etc. as necessary to get to 10 rows:
SELECT *
FROM `user_notifications`
ORDER BY `created_at` DESC
LIMIT 10
I think you just need a WHERE clause, to include both 2018 and 2019:
SELECT *
FROM user_notifications
WHERE YEAR(created_at) IN (2018, 2019)
ORDER BY created_at DESC
LIMIT 10;
If I've read it right, this sounds like just a simple ordering exercise
SELECT *
FROM user_notifications
WHERE created_at < :input_year + INTERVAL 1 YEAR
ORDER BY created_at DESC
LIMIT :offset, 10;
If you only want to go back one year you can just add another condition
SELECT *
FROM user_notifications
WHERE created_at < :input_year + INTERVAL 1 YEAR
AND created_at >= :input_year - INTERVAL 1 YEAR
ORDER BY created_at DESC
LIMIT :offset, 10;
Not that using a function like YEAR() on created_at rather than a comparison (<,>=) will prevent the engine from using an index on created_at
Use https://dev.mysql.com/doc/refman/8.0/en/year.html
SELECT *
FROM user_notifications
WHERE YEAR(created_at) <= $searchYear
ORDER BY created_at DESC
LIMIT 0, 10;
I have some code with me:
$sql = "SELECT * FROM palash ORDER BY id DESC LIMIT 31";
I want the LIMIT 31 to be LIMIT END OF THE MONTH
Use the LAST_DAY() function.
Takes a date or datetime value and returns the corresponding value for
the last day of the month. Returns NULL if the argument is invalid.
mysql> SELECT LAST_DAY('2003-02-05');
-> '2003-02-28'
mysql> SELECT LAST_DAY('2004-02-05');
-> '2004-02-29'
mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
-> '2004-01-31'
mysql> SELECT LAST_DAY('2003-03-32');
-> NULL
In your case do this:
SELECT *
FROM palash
WHERE your_date_column <= LAST_DAY(CURDATE())
ORDER BY id DESC
Avoid solutions like OlivierH's (no offense, Olivier). Functions applied on your columns make it impossible for MySQL to use an index.
You can limit to current month with this conditions :
SELECT *
FROM palash
WHERE MONTH(my_date_column) = MONTH(CURDATE())
AND YEAR(my_date_column) = YEAR(CURDATE())
You can then adjust it to get previous dates too.
EDIT / Other way : to stay close to your original idea and to still have a full SQL solution, you can get number of days in current month with LAST_DAY :
DAY(LAST_DAY(my_date_column))
Here is one way you can do it
CREATE TABLE [dbo].[Dates](
[DateColumn] [datetime] NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Dates]
([DateColumn])
VALUES
('2015-01-04 13:00:00'),
('2015-01-06 13:00:00'),
('2015-02-05 14:00:00')
GO
----Last Day of Current Month
Declare #LastDayOfCurrentMonth datetime = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
SELECT *
FROM Dates
Where DateColumn < #LastDayOfCurrentMonth
I have a mysql DB with tables, of which in the one table I have a date type field, I want the most recently passed date - so I want it to order by dates descending, but only take records from before today, and then take only the top most one using the LIMIT function, and also there is the addition of the WHERE clause being that the offer must be for the selected city.
$result = mysql_query("
SELECT * FROM offers
WHERE city = ".$_SESSION["city"]."
ORDER BY exp_date DESC
LIMIT 0, 1");
ADD another condition to where clause
$result = mysql_query("
SELECT * FROM offers
WHERE city = ".$_SESSION["city"]." and Date < CURRENT_DATE()
ORDER BY exp_date DESC
LIMIT 1");
SELECT * FROM deals WHERE city = 2 AND exp_date < CURDATE()
ORDER BY exp_date DESC LIMIT 0, 1
Add the following condition to Where:
... and exp_date < CURDATE()
See http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html.