Mysql Select Before Time on date specified date - mysql

So I have table 'content' with structure like this :
con_id
con_showdate (Y-m-d)
con_showtime (H:i)
All I want to get is rows which con_showdate is passed or same as today, but if the con_showdate is today then get only rows where con_showtime is passed or same as recent time.
Rows :
`'1', 2018-10-24', '17:00';`
`'2', 2018-10-25', '11:00';`
`'3', 2018-10-25', '17:00';`
while recent date is 2018-10-25 and time is 12:00.
I tried :
SELECT * FROM content WHERE con_showdate <= CURRENT_DATE AND con_showtime <= CURRENT_TIME;
The result is :
`'2', 2018-10-25', '11:00';`
which is not showing all rows before today (row 1).
Thank you for the effort.

You can use select all old dates and compare time only if date equals today's date, using OR as
SELECT * FROM content WHERE con_showdate < CURRENT_DATE OR ( con_showdate = CURRENT_DATE and con_showtime <= CURRENT_TIME) ;

Related

MySQL Query Group By Date (12 hours Interval)

I wrote a sql query for getting number of users created in a period of time for plotting graph (grafana or chart js) , and my sql query is
SELECT
date(user.created_date) as "time",
count(distinct user.id) as Number Of User,
status as status
FROM user
WHERE
created_date >= FROM_UNIXTIME(1649635200) AND
created_date < FROM_UNIXTIME(1649894399)
GROUP BY user.status, date(user.created_date)
ORDER BY date(user.created_date)
Here in this query created date is passed dynamically from front-end,
Now i am getting the result like,
Now whenever i select the date filter from last 24 hours/12 hours some of the result is not there,
Is there is any way to modify my sql query to group by created_date with 12 hour interval
For Example, Now query result is 11/04/2022 - 5 Users(Application Created) I want query result like this 11/04/2022 00:00:00 2 - 2 users created 11/04/2022 12:00:00 - 3 users created
In grafana there is a filed $__timeFrom() and $__timeTo()
On the basis of this I rewrite my query:
SELECT
(CASE
WHEN HOUR(TIMEDIFF($__timeFrom(), $__timeTo())) <= 24
THEN user.created_date
ELSE date(user.created_date) end) AS "time",
count(distinct user.id) as Users,
FROM user
WHERE
user.created_date >= $__timeFrom() AND
user.created_date < $__timeTo() AND
GROUP BY CASE
when HOUR(TIMEDIFF($__timeFrom(), $__timeTo())) <= 24
then user.created_date
else date(created_date) end
ORDER BY CASE
when HOUR(TIMEDIFF($__timeFrom(), $__timeTo())) <= 24
then user.created_date
else date(created_date) end;
If you use this expresion in your GROUP BY, you'll get a 12-hour grouping.
DATE(created_date) + INTERVAL (HOUR(created_date) - HOUR(created_date) MOD 12) HOUR
You can, if you have the priv, declare a stored function to make this easier to read.
DELIMITER $$
DROP FUNCTION IF EXISTS TRUNC_HALFDAY$$
CREATE
FUNCTION TRUNC_HALFDAY(datestamp DATETIME)
RETURNS DATETIME DETERMINISTIC NO SQL
COMMENT 'truncate to 12 hour boundary. Returns the nearest
preceding half-day (noon, or midnight)'
RETURN DATE(datestamp) +
INTERVAL (HOUR(datestamp) -
HOUR(datestamp) MOD 12) HOUR$$
DELIMITER ;
Then you can do
SELECT
TRUNC_HALFDAY(user.created_date) as "time",
count(distinct user.id) as Number Of User,
status as status
FROM user
WHERE
created_date >= whatever AND
created_date < whatever
GROUP BY user.status, TRUNC_HALFDAY(user.created_date)
ORDER BY TRUNC_HALFDAY(user.created_date)
Even though the function appears three times in your query, because it's declared DETERMINISTIC it only gets called once per row.
More complete writeup here.

How to SELECT all rows within a certain date/time range with a certain timestamp step size in MySQL?

I have a table that contains sensor data with a column timestamp that holds the unix timestamp of the time the sensor measurement has been taken.
Now I would like to SELECT all measurements within a certain date/time range with a specific time step.
I figured the first part out myself like you can see in my posted code snippet below.
// With $date_start and $date_stop in the format: '2010-10-01 12:00:00'
$result = mysqli_query($connection, "SELECT sensor_1
FROM sensor_table
WHERE timestamp >= UNIX_TIMESTAMP($date_start)
AND timestamp < UNIX_TIMESTAMP($date_stop)
ORDER BY timestamp");
Now is there a convenient way in MySQL to include a time step size into the same SELECT query?
My table contains thousands of measurements over months with one measurement taken every 5 seconds.
Now let's say I would like to SELECT measurements in between 2010-10-01 12:00:00 and 2010-10-02 12:00:00 but in this date/time range only SELECT one measurement every 10 minutes? (as my table contains measurements taken every 5 seconds).
Any smart ideas how to solve this in a single query?
(also other ideas are very welcome :))
Since you take one measurement every 5 seconds, the difference between $date_start and the first matching measurement cannot be greater than 4. We then take one entry every 600 seconds (allowing for some discrepancy from clock to clock...)
SELECT sensor_1
FROM sensor_table
WHERE timestamp >= UNIX_TIMESTAMP($date_start)
AND
timestamp < UNIX_TIMESTAMP($date_stop)
AND
((timestamp - UNIX_TIMESTAMP($date_start)) % 600) BETWEEN 0 AND 4
ORDER BY timestamp;
It is not elegant, but you can do:
SELECT s.sensor_1
FROM sensor_table s
WHERE s.timestamp >= UNIX_TIMESTAMP($date_start) AND
s.timestamp < UNIX_TIMESTAMP($date_stop) AND
s.timestamp = (SELECT MIN(s2.timestamp)
FROM sensor_table s2
WHERE s2.timestamp >= 60 * 10 * FLOOR(UNIX_TIMESTAMP(s.timestamp) / (60 * 10)) AND
s2.timestamp < s2.timestamp >= 60 * 10 * (1 + FLOOR(UNIX_TIMESTAMP(s.timestamp) / (60 * 10)))
)
ORDER BY timestamp;
This selects the first in each 10 minute period.
I think that you could use a simple cursor in plSQL
CREATE TABLE StoreValuesId
(
valueId int primary key;
)
CREATE OR REPLACE procedure_store[date_start date,date_stop date]
DECLARE date_startUpdated date , date_stopUpdated date , date_diff TIME(7) = '00:10:00'
IS
BEGIN
SELECT date_start INTO date_startUpdated;
SELECT date_stop INTO date_stopUpdated;
IF timestamp BETWEEN date_start and date_stop then
INSERT INTO StoreValuesId values(timestamp)
date_startUpdated=DATEADD(SECOND, DATEDIFF(SECOND, 0, date_diff), date_startUpdated);
date_stopUpdated=DATEADD(SECOND, DATEDIFF(SECOND, 0, date_diff), date_stopUpdated);
END IF
COMMIT;
END
Then again the syntax might be wrong but I hope you'll get the idea (haven't played with sql in a while)

ORDER BY datetime depending on the day AND time

I have a database field of type datetime.
The name of this field is "recallDate"
I would like to order the results in the following way:
The results must be chronological in the time: from newest to oldest
The results must be grouped by date: in other words, result having the same date are together, grouped
For every day, the results must be chronological according to the hour: earliest to latest
The results having no hour ( 00:00:00 ) have to be at the end of the results of the day
This is my actual query :
SELECT a.recallDate, a.id, a.id_company, com.name, a.recallType
FROM PDT_CRM.actions a
INNER JOIN PDT_CRM.traders as trad on trad.id=a.id_traders
WHERE DATE(a.recallDate) > DATE(NOW() + INTERVAL 30 DAY)
ORDER BY TIME(a.recallDate) , a.recallType
It is very likely that I have to use CASE but I don't understand how to use it.
You can use the following code to create a specific order that will put times '00:00:00' at the very end of the day:
...
ORDER BY date(a.rappelDate),
case when time(a.rappelDate) = 0 then 1 else 0 end,
time(a.rappelDate)

Put in where sql only the date from datetime

I have a table in my database like this :
id date origine
1 2015-12-04 16:54:38 1
Now I want to get only data witch have the date = 2015-12-04. So I tried like this :
select * from table where id = 1 and date = "2014-12-04"
But I have no data. Can you help me please ?
You can use the date function:
where id = 1 and date(date) = '2015-12-04'
However, for performance reasons, it is often better to use inequalities. This allows MySQL to use an index on id, date for the query:
where id = 1 and
(date >= '2015-12-04' and date < date_add('2014-12-04', interval 1 day))
you can use Date Function of mysql which returns date from DateTime or truncate the Time part
select * from table where id = 1 and Date(date) = "2014-12-04"
There are several date related function out there you can use, take the following:
select *
from table
where id = 1
and date_format(date, '%Y-%m-%d') = '2015-12-04';
date_format will format your date column to a particular format.
In MSSQL you can simply say
SELECT *
FROM Table
WHERE ID = 1
AND Date > '2015-12-04'
I'm not familiar with mysql, but I assume something similar would work here. This date gets formatted as 2015-12-04 00:00:00 so in effect it matches everything with a date of 2015-12-04 and a time greater than 00:00:00.
If you happen to have rows with time of 00:00:00, just use >= instead.

My join sql query won't bring results

What could be wrong with my sql query here , I'd like to retrieve data from both tables meeting a WHERE condition
SELECT *, UNIX_TIMESTAMP(i.sent_date) AS udate
FROM ibc_sent_history as i INNER JOIN
ibc_messages as u
ON i.msg_ids = u.id
WHERE (i.sent_date >= '02-02-2013' AND i.sent_date <= '02-02-2014')
ORDER BY i.sent_date
LIMIT 200
Assuming your ibc_sent_history.sent_date datatype is DATETIME, here's a way to refactor this query. (This will work even if the datatype is DATE). You need to change your date input string format from 02-02-2013 to the more standard '2014-02-02` (YYYY-MM-DD).
SELECT whatever, whatever
FROM ibc_sent_history AS i
INNER JOIN ibc_messages AS u ON i.msg_ids = u.id
WHERE i.sent_date >= '2013-02-02'
AND i.sent_date < '2014-02-02' + INTERVAL 1 DAY
ORDER BY i.sent_date DESC
LIMIT 200
I changed the ORDER BY to include DESC. This is to return the most recent items, not the oldest. If that's not what you need, take off the DESC.
I changed the date formatting.
I changed the end of your selection range to
i.sent_date < '2014-02-02` + INTERVAL 1 DAY
That's because
i.sent_date <= '2014-02-02`
will include items that occur precisely at midnight on 2-Feb-2014, but won't include any other items on that day. What you probably want are items that occurred up to but NOT including midnight on the next day.
I don't know MySQL very well, but in SQL Fiddle when I run:
CAST('2014-02-02' AS DATE)
I get a date, when I run
CAST('02-02-2014' AS DATE)
I get NULL, so seems like your date format is wrong.
Demo: SQL Fiddle