MySQL using BETWEEN not returning anything? - mysql

I am trying to get all rows from my MySQL database that are from the last week and also have the right company_id. I don't understand why this isn't returning any data, as there are no errors.
A screenshot of the database:
My code:
// Create Calendar and Date objects
Calendar calendar = Calendar.getInstance();
java.sql.Date date = new java.sql.Date(calendar.getTime().getTime());
// Get all datapoints from last week from this company's id
query = "SELECT * FROM survey_data WHERE (company_id = ?) AND (date_entered BETWEEN ? + interval ? day AND ? + interval ? day)";
preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, companyId);
preparedStatement.setDate(2, date);
preparedStatement.setInt(3, -Calendar.DAY_OF_WEEK - 6);
preparedStatement.setDate(4, date);
preparedStatement.setInt(5, -Calendar.DAY_OF_WEEK);
resultSet = preparedStatement.executeQuery();

Related

show mysql average of the last 14 days in a c# application

I have a mysql table with the columns ID, name, gold and timestamp.
This table shows with the following statement the average of the gold of the respective item(name). But now the database is already filled with 90k entries and the average should only be limited to 2 weeks. Here is the code:
`
private DataTable GetAverageGold()
{
var dtAverageGold = new DataTable();
var percentageBuy = double.TryParse(textBox1.Text.Replace("%", string.Empty), out var sell) ? sell / 100 : 0.02;
using (_con = GetMySqlConnection())
{
using (var cmd = new MySqlCommand(
"SELECT name AS name, FORMAT(GROUP_CONCAT(gold ORDER BY id DESC), 'de_DE') AS 'MOST RECENT', FORMAT(ROUND(AVG(gold) - AVG(gold) * " +
percentageBuy.ToString(CultureInfo.InvariantCulture).Replace(",", ".") +
"), 'de_DE') AS Einkaufspreis, FORMAT(ROUND(AVG(gold)),'de_DE') AS Durchschnitt, ROUND((AVG(gold) - GROUP_CONCAT(gold ORDER BY id DESC)) / GROUP_CONCAT(gold ORDER BY id DESC) * 100,2) AS 'profit in %' FROM items GROUP BY name ORDER BY Name",
_con))
{
try
{
_con.Open();
var reader =
cmd.ExecuteReader();
dtAverageGold.Load(reader);
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString(), "Error in: GetAverageGold", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
_con.Close();
}
}
}
return dtAverageGold;
}
`
I tried "WHERE timestamp <= NOW() + INTERVAL 14 DAY GROUP BY name ORDER BY name" at the end of the statement. but it did not help. The syntax seems to be correct, as I get no error, but the average still refers to all entries
You were thinking along the right lines but it should have been -
WHERE timestamp >= NOW() - INTERVAL 14 DAY
or
WHERE timestamp >= CURRENT_DATE - INTERVAL 14 DAY

Google Script MYSQL QUERY with Variables from google sheets

Ok so I've been pretty much learning on my own and I ran into a problem that I cant seem to find a solution for.
The main goal is I have a google sheet with a start and end date that the user can change, the script pulls those dates and uses them in a MySQL query to pull the data between that date range.
Example: start date = 10/1/2021, end date = 10/22/21
Query: "select * from Table, where table.date >= start date AND table.dat <= end date"
See my code example below:
======================================================
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('DR_Campaign_Report');
var getStartDate = sheet.getRange(1,2).getValue();
var startDate = Utilities.formatDate(getStartDate,"GTM","MM/dd/yyyy");
var getEndDate = sheet.getRange(1,5).getValue();
var endDate = Utilities.formatDate(getEndDate,"GTM","MM/dd/yyyy");
var conn = Jdbc.getConnection(url, username, password);
var stmt = conn.createStatement();
var results = stmt.executeQuery
( 'SELECT m.Campaign as "Campaign",\n' +
'count(m.Campaign) as "Leads",\n' +
'count(m.Duplicate) as "Dups",\n' +
'count(m.Campaign) - count(m.Duplicate) as "Valid Leads",\n' +
'count(m.AppSet) as "Appts",\n' +
'SUM(IF(m.ZepID != "",1,0)) as "Transferred Appts"\n' +
'FROM intakeMani m\n' +
'WHERE date(m.IncomingDate) >= date('startDate') and date(m.IncomingDate) <= date('endDate')\n' +
'OR date(m.AppSet) >= date('startDate') and date(m.AppSet) <= date('endDate')\n' +
'GROUP BY m.Campaign with rollup'
);
The Error is here in the WHERE clause when its attempting to pull the google script variables startDate and endDate.
'WHERE date(m.IncomingDate) >= date('startDate') and date(m.IncomingDate) <= date('endDate')\n' +
'OR date(m.AppSet) >= date('startDate') and date(m.AppSet) <= date('endDate')\n' +
I attempted the double "'startDate'" and is still errors. see attached pic.
I fixed it, I had double " in the var getStartDate/GetEndDate fields and need to add " to the query "'+startdate+'"
Thank you for your help.

EF6 generating date comparison sql for MySql database

I have a web app built in .NETCore 2.1 which calls an API built in .Net 4.6. The API calls a services layer which is using entity framework 6. I'm connecting to a MySql database. I'm using the Pomelo.EntityFrameworkCore.MySql connector. When using a LINQ query to get records based on a date comparison, EF6 appears to be cmparing the dates as string literals.
I've tried all different types of variations of the LINQ query and looked online for extension libraries that do date comparisons, but to no avail
Here's the LINQ query
int year = DateTime.Now.Year;
DateTime firstDayOfYear = new DateTime(year, 1, 1);
DateTime lastDayOfYear = new DateTime(year, 12, 31);
var startDate = firstDayOfYear.AddYears(-2);
var endDate = lastDayOfYear.AddYears(-1);
var company = dbContext.Companies.Where(c =>
c.Updating &&
c.UpdatedBy == username &&
c.LastUpdate > startDate &&
c.LastUpdate < endDate)
.FirstOrDefault();
Here's part of the SQL that is generated. note the # symbols before the date values
`Extent2`.`ID` AS `ID1`,
`Extent2`.`Name` AS `Name1`
FROM Company AS `Extent1` INNER JOIN `Table_2` AS `Extent2` ON `Extent1`.`ID` = `Extent2`.`ID`
WHERE ((((`Extent1`.`SomeFlag` != 1) AND (`Extent1`.`LastUpdate` > #'01/01/2017 00:00:00')) AND (`Extent1`.`LastUpdate` < #'31/12/2017 00:00:00')) AND ((`Extent1`.`ID` IN ( '1','2','6','7','8' )) AND (`Extent1`.`ID` IS NOT NULL))) AND (NOT ((`Extent1`.`Telephone` IS NULL) OR ((LENGTH(`Extent1`.`Telephone`)) = 0)))) AS `Project1`
Running the sql query manually in MySql workbench returns no rows. if I remove the # symbols it does return rows, as expected. What am I doing wrong?
I couldn't figure out why EF was translating the LINQ that way so I just used a stored procedure call to get round it. At least then I could write the SQL myself.
int year = DateTime.Now.Year;
DateTime firstDayOfYear = new DateTime(year, 1, 1);
DateTime lastDayOfYear = new DateTime(year, 12, 31);
var startDate = firstDayOfYear.AddYears(QueueConfig.UpdateQueueStartDateInYears);
var endDate = lastDayOfYear.AddYears(QueueConfig.UpdateQueueStartDateInYears);
var userParam = new MySql.Data.MySqlClient.MySqlParameter("userName", username);
var sdParam = new MySql.Data.MySqlClient.MySqlParameter("startDate", startDate);
var edParam = new MySql.Data.MySqlClient.MySqlParameter("endDate", endDate);
var lockedCompany = dbContext.Database.SqlQuery<CompanyDto>("CALL GetLockedCompany(#userName,#startDate,#endDate)", userParam, sdParam, edParam);
var companyDto = lockedCompany.SingleOrDefault();

Selecting rows that are within 2 hours from current time

I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);

calculate the time passed after an entry of date with the current time of the day

PreparedStatement pStmt = con.prepareStatement("insert into mydate values(?,?)");
java.util.Date now = new java.util.Date();
pStmt.setDate( 1, new java.sql.Date( now.getTime()) );
pStmt.setTimestamp( 2, new java.sql.Timestamp( now.getTime() ) );
pStmt.executeUpdate();
QUERY1:
I am creating post a comment module .I want to display the time when user posted their comments.also i want to show the time passed after they have posted a comment.
like 2 days ago ,5 min before etc.
QUERY2:
i also want to change the format of the date to dd/mm/yyyy.
For displaying the date formatted you can use java.text.SimpleDateFormat or
org.apache.commons.lang.time.FastDateFormat
For the time intervals you can use org.apache.commons.lang.time.DurationFormatUtils
Here is a sample:
//this will get the date in format dd/mm/yyyy
FastDateFormat fmt = FastDateFormat.getInstance("dd/MM/yyyy");
String txt = fmt.format(date);
//this will get the interval
long ival = System.currentTimeMilis()-date.getTime();
String interval = DurationFormatUtils.formatDurationWords(ival, true, true);