How to compare date object in mysql against two string dates? [duplicate] - mysql

This question already has answers here:
How to convert a string to date in MySQL?
(5 answers)
Closed 2 years ago.
I am trying to compare the following:
SELECT g_m.user_id
, g_m.group_id
FROM Group_Members g_m
WHERE g_m.gender_id = 2
AND g_m.partner_gender_id = 1
AND g_m.birthday >= '01-01-1955'
AND g_m.birthday <= '12-31-2002'
AND g_m.user_id != 12
g_m.birthday in this case is '02-15-1998' which should show up, but this returns an empty array, because the date comparison does not seem to be accurate?
Here is the entire function and the dates are being passed from age minimum and age maximums brought from user.
var today = new Date();
var minYear = "01-01-" + (today.getFullYear() - userPref.age_max); //min year to start but oldest age
var maxYear = "12-31-" + (today.getFullYear() - userPref.age_min); //max year to end but youngest age
var qSelect = "SELECT g_m.user_id, g_m.group_id" +
" FROM Group_Members g_m WHERE g_m.gender_id = ? AND g_m.partner_gender_id = ?" +
" AND g_m.birthday >= STR_TO_DATE(?, '%m/%d/%Y') AND g_m.birthday <= STR_TO_DATE(?, '%m/%d/%Y')" +
" AND g_m.user_id != ?";
var qValues = [userPref.partner_gender_id, userObj.gender_id, minYear, maxYear, userObj.id];
Anyone know how to compare dates in a mysql query?

What is the data type of your dates ? You should declare them as "date", otherwise you won't be able to compare them.
With strings, '02-15-1998' < '03-15-1990'
With dates, your mysql request should be :
SELECT g_m.user_id, g_m.group_id FROM Group_Members g_m WHERE g_m.gender_id = 2 AND g_m.partner_gender_id = 1 AND g_m.birthday >= '1955-01-01' AND g_m.birthday <= '2002-12-31' AND g_m.user_id != 12
Sorry for my english, I'm french...

As the comments have already pointed out, you appear to be storing your dates as actual text. For a short term workaround, you may use STR_TO_DATE to convert your text dates to bona fide MySQL dates. Then, compare them against valid MySQL date literals:
SELECT
g_m.user_id,
g_m.group_id
FROM Group_Members g_m
WHERE
g_m.gender_id = 2 AND
g_m.partner_gender_id = 1 AND
STR_TO_DATE(g_m.birthday, '%m-%d-%Y') >= '1955-01-01' AND
STR_TO_DATE(g_m.birthday, '%m-%d-%Y') < '2003-01-01' AND
g_m.user_id != 12;
Longer term, you should make the birthday column datetime or timestamp.
Side note: I have rewritten the date range to include those born in the calendar years from 1955 to 2002, inclusive on both ends.

Related

Use Mysql function as column name in select query in mysql

I have a mysql table with columns for each day of months. e.g., 1,2,3,4.. are column name. i want to select particular day column based on day present in emp.date.
I tried following query but it is not working.
SELECT emp.id
, emp.DATE_FORMAT(emp.date, "%d")
FROM emp_pattern_mapping epm
WHERE epm.year = 2019
AND epm.month = 8
AND epm.type = 2
AND epm.emp_id = 39;
It is giving column not found error
You have a very poor data format and you should devote your effort to fixing it.
You can do what you want with a giant CASE expression:
SELECT `emp`.`id`,
(CASE WHEN DAY(emp.date) = 1 THEN `1`
WHEN DAY(emp.date) = 2 THEN `2`
. . .
WHEN DAY(emp.date) = 31 THEN `31`
END)
FROM emp_pattern_mapping epm
WHERE epm.year = 2019 AND
epm.month = '08' AND
epm.type = 2 AND
epm.emp_id = 39;
Try this,
SELECT `emp`.`id`,DAY(emp.date) as emp_day
FROM emp_pattern_mapping epm
WHERE epm.year = 2019 AND
epm.month = '08' AND
epm.type = 2 AND
epm.emp_id = 39;

Manage Date in a Reservation System [duplicate]

This question already has answers here:
Booking Calendar Arrive & Depart Dates
(2 answers)
Closed 4 years ago.
Hi guys i'm creating a simple web application in Java in which i should book a room. Now my problem concerns the possibility of booking a room in the same period.
Let me explain better, I have 2 types of rooms, bedroom1 and bedroom2. If user1 has booked room1 on 22/08/2018, user2 can not book room1 on the same date.
Since I use a database I thought I could solve it by query.
In particular my database:
Table Name: reservation
id_book,login,email,typeroom,numroom,arrivaldate,departuredate.
I have tried to use this query:
SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate
FROM reservation res1, reservation res2
WHERE ( res1.typeroom = res2.typeroom ) AND (res1.arrivaldate = res2.arrivaldate )
But I don't resolve the problem.
Can you help me??
UPDATE.
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
Statement stmt = con.createStatement();
out.println("connection successfull");
String check = ("SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate\n" +
"FROM reservation res1, reservation res2\n" +
"WHERE res1.numroom = res2.numroom\n" +
"AND ((res1.arrivaldate <= res2.departuredate AND res1.departuredate >= res2.arrivaldate)\n" +
" OR (res2.arrivaldate <= res1.departuredate AND res2.departuredate >= res1.arrivaldate))");
ResultSet rs2 = stmt.executeQuery(check);
int rs = st.executeUpdate("insert into reservation (login,email,typeroom,numroom,arrivaldate,departuredate)values ('"+login+"','"+email+"','"+typeroom+"','"+numroom+"','"+arrivaldate+"','"+departuredate+"')");
I'm trying first to use the database version of your answer. I have write this, to check if the booking is ok or not i should insert an if controller?
I think you mean overlap of reservations for the same room:
SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate
FROM reservation res1, reservation res2
WHERE res1.room_no = res2.room_no
AND res1.id_prenotazione != res2.id_prenotazione
AND res1.arrivaldate <= res2.departuredate AND res1.departuredata >= res2.arrivaldate
What should maybe checked too is: you used date equality. If that failed, maybe your table columns are not DATE but DATETIME/TIMESTAMP. That would be understandable
as someone might leave his room at 9:00 and the next enter at say 12:00.
AND (res1.arrivaldate = res2.arrivaldate ) would be wrong. You need a range
e.g AND (res1.arrivaldate > res2.arrivaldate ) AND (res1.arrivaldate < res2.departuredate) or something similar
If you want overlapping periods:
SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate
FROM reservation res1, reservation res2
WHERE ( res1.typeroom = res2.typeroom )
AND res1.id_book != res2.id_book
AND (res1.arrivaldate <= res2.departuredate)
AND (res2.arrivaldate <= res1.departuredate)

Query database for Current Week Results [duplicate]

I have table temp with structure on sqlfiddle:
id(int 11 primary key)
name(varchar 100)
name2(varchar 100)
date(datetime)
I would like get record on this week, example if now 21.11.2013 i would like all rows on 18.11.2013 to 24.11.2013(on week)
Now I see next algorithm:
obtain weekday
calculate how many days ago was Monday
calculate the date Monday
calculate future date Sunday
make a request on date
Tell me please, is exist a shorter algorithm (preferably in the query MySQL)?
ADD Question is: Why this query select record on date 17.11.2013(Sunday) - 23.11.2013(Saturday) and how get records on date 18.11.2013(Monday) - 24.11.2013(Sunday) ?
query:
select * from temp
where yearweek(`date`) = yearweek(curdate())
Thanks!
Use YEARWEEK():
SELECT *
FROM your_table
WHERE YEARWEEK(`date`, 1) = YEARWEEK(CURDATE(), 1)
Use YEARWEEK. If you use WEEKOFYEAR you will get records of previous years also.
SELECT id, name, date
FROM table
WHERE YEARWEEK(date)=YEARWEEK(NOW());
For selecting records of day, week and month use this way:
function my_func($time, $your_date) {
if ($time == 'today') {
$timeSQL = ' Date($your_date)= CURDATE()';
}
if ($time == 'week') {
$timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($time == 'month') {
$timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}
$Sql = "SELECT * FROM your_table WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}
You can do it by following method
SELECT DATE_FORMAT("2017-06-15", "%U");
Get number of week (From 00 to 53 )
Where (Sunday 1st day and Monday last day of week)
May be useful for you.
example:
SELECT DISTINCT DATE_FORMAT('dates', '%U') AS weekdays FROM table_name;
The short solution would be this:
SELECT * FROM my_table WHERE DATE_FORMAT("2021-08-19 15:40:33", "%U") = WEEK(CURDATE());

How to use between operator for 2 date input parameters in mysql?

My task is to get the records between 2fromdate and todate(given as a input parameters).
i am not able to use between operator for 2 input parameters...
My query as follows...
DELIMITER $$
CREATE DEFINER=`testrunner`#`%` PROCEDURE `usp_GetAllTranasactions`(pFromDate nvarchar(30),pToDate nvarchar(30),pstatus int)
BEGIN
select
ST.UserID,U.Username,
ST.SubscriptionID,
ST.DateOfSubscription,
SM.SubType,
SM.Details,
ST.Amount,
ST.EndDate,
ST.Status
from tr_t_subscriptiontransactions ST
Join tr_m_users U on U.UserID=ST.UserID
join tr_m_subscription SM on SM.SubscriptionID=ST.SubscriptionID
where **ST.DateOfSubscription between (pFromDate and pToDate) and ST.EndDate
between(pFromDate and pToDate) and ST.Status=pstatus;**
END if;
END
here i don't know how to use between parameters..plz help me..i want to retrive record between fromdate and todate..hope u understand..
Let us assume you want all transactions for the month of June 2014
In your user interface the parameter values are:
from_date = 2014-06-01
to_date = 2014-06-30
But you will evaluate against a transaction date & time. How do you ensure that absolutely every transactions on June 30 - right up to midnight - is included in the results?
Here is how: use 2014-07-01 instead of 2014-06-30, and here is what the query would look like - which does NOT use between!
SELECT
ST.UserID
, U.Username
, ST.SubscriptionID
, ST.DateOfSubscription
, SM.SubType
, SM.Details
, ST.Amount
, ST.EndDate
, ST.Status
FROM tr_t_subscriptiontransactions ST
JOIN tr_m_users U
ON U.UserID = ST.UserID
JOIN tr_m_subscription SM
ON SM.SubscriptionID = ST.SubscriptionID
WHERE (ST.DateOfSubscription >= pFromDate AND ST.DateOfSubscription < pToDate + 1)
AND (ST.EndDate >= pFromDate AND ST.EndDate < pToDate + 1)
AND ST.Status = pstatus
;
AVOID between for date ranges because it INCLUDES both the lower and upper boundary values.
... equivalent to the expression (min <= expr AND expr <= max)
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
What this can lead to is an "anti-pattern" which look like this:
where dt_field between '2014-06-01 00:00:00' and '2014-06-30 23:59:59'
but there are time units smaller than one second, so that approach is imperfect. Don't attempt to overcome the deficiencies of between by adjusting the upper value this way. The simple and more accurate approach is to use >= and < adjusting the upper value by one whole time unit (usually the next day).

Beginner LINQ syntax question

I have a basic SQL Table ( pKey INT, TransDate smallDateTime, Amount Float)
I simply want to emulate this SQL in LINQ
SELECT SUM(Amount) AS result
FROM dbo.Basic
WHERE TransDate >= #startDate
AND TransDate <= #EndDate
I have created the LINQ dbml for this and I can get basic query results for a date range
However I can't find the right syntax to get the SUM over a dateRange, I've tried several variations on the following but either they dont compile, or the result they give cannot be converted to a double
BasicDataContext dContext = new BasicDataContext();
var lnq = from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select new { total = c.Sum(Amount) };
double result = (double)lnq.total;
This should work:
double result = (from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select c.Amount).Sum();