when i pass date through variables inside query don't get output - php

I am facing a very strange issue trying to solve it since last 6 hours but all in vain. When i store date inside the variable the query shows 0 results. But when i store date date directly inside query it gives me output. But if i store date inside variable like below it does not give me any output.
$fromdate="2020-01-08";
$todate='2020-08-14';
And below is a query
"SELECT A1.u_id_fk, A3.full_name, A1.created AS check_in_at, A2.created AS check_out_at, TIMEDIFF(A2.created, A1.created) AS total_time
FROM timesheet
AS A1 INNER JOIN timesheet AS A2 ON A1.u_id_fk = A2.u_id_fk AND DATE(A1.created) = DATE(A2.created)
INNER JOIN users A3 on A1.u_id_fk=A3.u_id
WHERE 1 = 1 AND A1.status = 'Check-In' AND A2.status = 'Check-Out'
AND DATE(A1.created) BETWEEN :fromdate AND :todate
AND DATE(A2.created) BETWEEN :fromdate AND :todate
ORDER BY A1.created DESC"
above query only returns rows when i provide date directly inside query such '2020-01-08' instead of :fromdate and :todate.

Related

Find record older / newer than the current record in SQL

I am trying to write a SQL statement that gives me a previous / next record.
My posts table has records that are either a blog post or a ships log (based on the column posts_isLog being either a 1 or 0).
I am using the following prepared statement to return the current ships log based on the date. The column post_createdOn is a date/time data type. I am using a like statement to match my passed date to the query as this is found via the URL so "shipslog/14th-April-2020". The date is changed to match the data so yyyy-mm-dd so no issues there.
//query
$this->db->query('SELECT *
from posts
INNER JOIN voyages ON posts.post_voyage = voyages.voyage_id
WHERE post_createdOn LIKE :date
AND post_isLog = 1
AND post_live = 1');
//bind values
$this->db->bind(':date', '%'.$date.'%');
//get the results
$row = $this->db->single();
return $row;
I can't work out the SQL to use find the next / previous ships log based on the current record.
I think what I am looking to write is something like... "Select all from posts where post_createdOn is less than the current record's post_createdOn date".
I am trying
//query
$this->db->query('SELECT *
from posts
WHERE post_createdOn < :date
AND post_isLog = 1
AND post_live = 1');
//bind values
$this->db->bind(':date', '%'.$date.'%');
//get the results
$row = $this->db->single();
return $row;
But I know this isn't referring to the current record. Completely stumped!
This is the refering $this->db->single();
//get single record as an object
public function single() {
$this->execute();
return $this->statement->fetch(PDO::FETCH_OBJ);
}
Thanks to all the answers!
It seems I was nearly there after #RiggsFolly's help. I took out the % and the query returned a result. I needed to order the results as I was only returning the first row!
public function getPreviousLog($date) {
//query
$this->db->query('SELECT *
from posts
WHERE post_createdOn < :date
AND post_isLog = 1
AND post_live = 1
ORDER BY post_createdOn DESC');
//bind values
$this->db->bind(':date', $date);
//get the results
$row = $this->db->single();
}
You could use LAG and LEAD for this but it's a bit tedious if you have a lot of columns. Instead try:
WITH cte AS(
SELECT *, ROW_NUMBER() OVER(ORDER BY post_CreatedOn) rn
FROM posts
WHERE
post_createdOn < :date AND
post_isLog = 1 AND
post_live = 1
)
SELECT *
FROM
cte curr
LEFT JOIN cte next ON curr.rn+1 = next.rn
LEFT JOIN cte prev ON curr.rn-1 = prev.rn
You don't seem to specify any partition - you just say that your table is one long stream of dated records and each record has a prev and a next according to the date. If there is some sort of notion that groups of columns belong together, put the thing that groups them into the row number as a PARTITION BY and also add it to the join ON clauses between prev curr and next
I'm not entirely clear on whether you want the "next" row if it it outside the date limit. Eg if you have two rows 2000-12-31 and 2001-01-01 and you set your date parameter to 2001-01-01 then the later record will be excluded as "current" but does it mean that the 2000-12-31 row should have a "next" that is null, or is the 2001-01-01 row
If it should (this query will not return it) take the predicate out of the CTE and put it in the main query WHERE, on curr.post_createdOn instead
If you're making some kind of pagination system, with one log per day and you want 3 rows, consider:
WITH cte AS(
SELECT *
FROM posts
WHERE
post_isLog = 1 AND
post_live = 1
)
SELECT. *
FROM cte
WHERE post_createdOn IN(
SELECT MAX(post_createdOn) FROM cte WHERE post_createdOn < #date
UNION ALL
SELECT #date
SELECT MIN(post_createdOn) FROM cte WHERE post_createdOn > #date
)

Getting all id's of group with recent record in mysql

I have users with different group code in my MySQL database. I am saving their latitude and longitude in database according to their current positions.
Problem is I am not able to get their recent records according to their group code.
I have tried this
SELECT * FROM tracklatlong WHERE id IN (SELECT MAX( id ) FROM
tracklatlong GROUP BY 'track_CfiUw');
but i am only getting last record of this track_CfiUw group code.
i want result like below
Your query should be like,
SELECT tl1.id,tl1.admin_id,tl1.name,tl1.groupcode
FROM tracklatlong tl1
LEFT JOIN tracklatlong tl2 ON (tl1.name = tl2.name AND tl1.id < tl2.id)
WHERE tl2.id IS NULL AND tl1.groupcode = 'track_CfiUw';
But instead you are grouping it by group_code value.

match date in mysql and give result

I have written query in mysql as
select * from tblstafftasks as tst join tblstafftaskassignees as tsta on tsta.taskid = tst.id join tblstaff as ts on ts.staffid = tsta.staffid where tst.startdate like '2016-07-21' or '2016-07-21' between tst.startdate and tst.duedate and tst.rel_id = 1
My database looks like :
When I have written above query it runs perfect but does not give any result.
Here I have used 2016-07-21 that match with the startdate so it not give any result. So what query should I have to write to get result if it match with the startdate.?
Here i pass date in simple Y-m-d format and in database it store as datetime so help me to solve this query.
It seems like you want to compare a date with DATETIME data types. If you want to compare just with the date of the DATETIME field, do something like this:
SELECT * FROM tblstafftasks AS tst
JOIN tblstafftaskassignees AS tsta ON tsta.taskid = tst.id
JOIN tblstaff AS ts ON ts.staffid = tsta.staffid
WHERE DATE(tst.startdate) <= '2016-07-21'
AND DATE(tst.duedate) >= '2016-07-21'

How to calculate difference between values coming from the same row in mysql

I am trying to calculate the difference of values list coming from a database.
I would like to achieve it using php or mysql, but I do not know how to proceed.
I have a table named player_scores. One of its rows contains the goals scored.
Ex.
pl_date pl_scores
03/11/2014 18
02/11/2014 15
01/11/2014 10
I would like to echo the difference between the goals scored during the matches played in different dates.
Ex:
pl_date pl_scores diff
03/11/2014 18 +3
02/11/2014 15 +5
01/11/2014 10 no diff
How can I obtain the desired result?
You seem to want to compare a score against the score on a previous row.
Possibly simplest if done using a a sub query that gets the max pl_date that is less than the pl_date for the current row, then joining the results of that sub query back against the player_scores table to get the details for each date:-
SELECT ps1.pl_date, ps1.pl_scores, IF(ps2.pl_date IS NULL OR ps1.pl_scores = ps1.pl_scores, 'no diff', ps1.pl_scores - ps1.pl_scores) AS diff
FROM
(
SELECT ps1.pl_date, MAX(ps2.pl_date) prev_date
FROM player_scores ps1
LEFT OUTER JOIN player_scores ps2
ON ps1.pl_date > ps2.pl_date
GROUP BY ps1.pl_date
) sub0
INNER JOIN player_scores ps1
ON sub0.pl_date = ps1.pl_date
LEFT OUTER JOIN player_scores ps2
ON sub0.prev_date = ps2.pl_date
There are potentially other ways to do this (for example, using variables to work through the results of an ordered sub query, comparing each row with the value stored in the variable for the previous row)
SELECT score FROM TABLE WHERE DATE = TheDateYouWant
$score = $data['score'];
SELECT score FROM TABLE WHERE date = dateYouWant
$difference = $score - $data['score'];
Something like this?
You could use two queries, one to get the value to use in the comparison (in the example below is the smaller number of scores) and the second one to get the records with a dedicated column with the difference:
SELECT MIN(pl_scores);
SELECT pl_date, pl_scores, (pl_scores - minScore) as diff FROM player_scores;
Or, using a transaction (one query execution php side):
START TRANSACTION;
SELECT MIN(Importo) FROM Transazione INTO #min;
SELECT Importo, (Importo - #min) as diff FROM Transazione;
select *,
coalesce(
(SELECT concat(IF(t1.pl_scores>t2.pl_scores,'+',''),(t1.pl_scores-t2.pl_scores))
FROM tableX t2 WHERE t2.pl_date<t1.pl_date ORDER BY t2.pl_date DESC LIMIT 1)
, 'no data' ) as diff
FROM tableX t1
WHERE 1
order by t1.pl_date DESC

Assistance with Search MySql DB using date and time range

I have a search page for my users and one of the things I want them to be able to do is search items in our DB using a time range.
Currently, my query looks like this:
select ****
from ****
where created_on >='{$errTimeDayOne}' and created_on <= '{$errTimeDayTwo}'
So, say $errTimeDayOne = 2013-03-24 00:00:00 and $errTimeDayTwo = 2013-04-01 01:00:00 it will search between that range. I'm trying to search between 00:00:00 - 01:00:00 through dates 2013-03-24 - 2013-04-01. Any thoughts or suggestions?
Update:
My query now looks like this:
SELECT call_id, priority_name, caller_name,
cust_name, cust_rep, caller_dept,
DATE_FORMAT(created_on , '%Y-%m-%d') AS created_on,
DATE_FORMAT(updated_on, '%Y-%m-%d') AS updated_on,
source_name, created_by, cat_name, subcat_name
FROM calls INNER JOIN categories ON calls.cat_id =
categories.cat_id INNER JOIN ticket_priority ON
calls.ticket_priority = ticket_priority.priority_id
INNER JOIN ticket_source ON calls.ticket_source =
ticket_source.source_id LEFT OUTER JOIN subcategories
ON calls.subcat_id = subcategories.subcat_id WHERE
created_by = 'brett.little' AND (DATE(created_on)
between '2013-03-01' and '2013-08-01') AND
(TIME(created_on) between '1:00:00' and '16:00:00')
It is displaying results when I leave out '(TIME(created_on) between '1:00:00' and '16:00:00')'. Might this have anything to do with the date_format in the beginning of the query?
You'll have to enhance the clause to check the times and dates separately:
WHERE (DATE(created_on) BETWEEN '2013-03-24' and '2013-04-01')
AND (TIME(created_on) BETWEEN '00:00:00' AND '01:00:00')

Categories