MySQL conditional query inside where clause - php

I'm not sure if I'm missing something really obvious, but I keep getting a syntax error on this query. Even if I AM missing something obvious, I'd like to know if there is a smarter way of getting what I'm after.
Basically, the query asks for any rows tied to a user with a start_date between Monday and Friday. That works great. But then I added a conditional query in case there are any rows for that Saturday or Sunday. Note that the conditional query is checking for ANY users with a Saturday or Sunday, not the user in the main query:
SELECT user_id,
DATE_FORMAT(DATE(shift_start),'%m/%d/%Y') date,
TIME_FORMAT(TIME(shift_start), '%h:%i %p') start,
TIME_FORMAT(TIME(shift_end), '%h:%i %p') end,
title
FROM shifts
WHERE user_id = '$user_id'
AND DATE(shift_start) BETWEEN
DATE_SUB(DATE(NOW()), INTERVAL WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL
(SELECT
IF(
COUNT(*) FROM shifts
WHERE DATE(shift_start) BETWEEN
DATE_ADD(DATE(NOW()), INTERVAL 5 - WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL 6 - WEEKDAY(NOW()) DAY),
6, 4)) - WEEKDAY(NOW()) DAY)
ORDER BY shift_start
I'm actually pretty proud of how it works before it messes up with the IF part, but again, if there is an obviously better way doing this, I'm all ears.
Oh, and when this gets ironed out, the "Now()" will be replaced with a date variable set up in the php script (passed to it via GET).
Awesome job, benlumey. Here's what worked:
SELECT user_id,
DATE_FORMAT(DATE(shift_start),'%m/%d/%Y') AS shift_start_date,
TIME_FORMAT(TIME(shift_start), '%h:%i %p') AS shift_start_time,
TIME_FORMAT(TIME(shift_end), '%h:%i %p') AS shift_end_time,
title
FROM shifts
WHERE user_id = '$user_id' AND
DATE(shift_start) BETWEEN
DATE_SUB(DATE(NOW()), INTERVAL WEEKDAY(NOW()) DAY)
AND
DATE_ADD
(
DATE(NOW()), INTERVAL
(
SELECT IF(COUNT(*),6,4)
FROM shifts
WHERE DATE(shift_start) BETWEEN
DATE_ADD(DATE(NOW()), INTERVAL 5 - WEEKDAY(NOW()) DAY)
AND
DATE_ADD(DATE(NOW()), INTERVAL 6 - WEEKDAY(NOW()) DAY)
) - WEEKDAY(NOW()) DAY
)

Try this subquery:
(SELECT
IF(COUNT(*) > 0, 6, 4)) - WEEKDAY(NOW()) DAY)
FROM shifts
WHERE DATE(shift_start) BETWEEN
DATE_ADD(DATE(NOW()), INTERVAL 5 - WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL 6 - WEEKDAY(NOW()) DAY)
Two things I've done
made it look like a normal query, the from and where can't go inside the if as far as i'm aware.
Put a condition in the if, don't think mysql will automatically take 0 as false and >0 as true.

this falls apart around here:
(SELECT
IF(
COUNT(*) FROM shifts
WHERE DATE(shift_start) BETWEEN
The count statement won't work.
What are you trying to do? You need a clear statement of what you are trying to accomplish here.
This is my swag at it:
(SELECT
IF(
(select COUNT(*) FROM shifts
WHERE DATE(shift_start) BETWEEN
DATE_ADD(DATE(NOW()), INTERVAL 5 - WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL 6 - WEEKDAY(NOW()) DAY))>0,6,4)
) - WEEKDAY(NOW()) DAY
But without knowing what you are trying to do I'm not sure.

Related

select row that is - 24 hours to go

In my DB I have a column called dato_tid (Datatype = date)
right now I have 2 post
1 where the date is 2018-07-18
2 where the date is 2018-07-20
I need to select the post, that has less then 24 hours to go
SELECT * FROM `udflyt` WHERE dato_tid > DATE_ADD(CURDATE(), INTERVAL -1 day)
this line will select both posts
SELECT * FROM `udflyt` WHERE dato_tid > DATE_ADD(CURDATE(), INTERVAL -24 HOUR)
and so will this, I did try to change the > to < but the same.
SELECT * FROM `udflyt` WHERE dato_tid > (now() - interval 1 day )
this line will also get both posts
So what do I need to do, Thanks
Actually, 24 hours to go means you should ADD a day, not subtract a day.
SELECT *
FROM `udflyt`
WHERE dato_tid <= DATE_ADD(CURDATE(), INTERVAL +1 day);
Will provide only the record with date '2018-07-18' (which is what you are looking for, I believe.
The below shows the values used for comparison for both doing addition and subtraction.
SELECT *, DATE_ADD(CURDATE(), INTERVAL +1 day), DATE_ADD(CURDATE(), INTERVAL -1 day)
FROM `udflyt`
WHERE dato_tid <= DATE_ADD(CURDATE(), INTERVAL +1 day);

How to filter last one week data on a specific day

Hi I have a MySQL database that already has auto increment date time colomn (may information help).
How to filter last one week data as start from specific day until next 7 day.
example. Show data from Wednesday on this week until nest 7 day
$query="SELECT * FROM diagnosa WHERE schedule= '$a'";
$a is start day the data start to be shown (example Wednesday)
This may help you...
SELECT *
FROM table
WHERE date_colunm between 'start_date' AND DATE_ADD("start_date", INTERVAL 7 DAY);
UPDATE :
As you need from the Wednesday. Please us below query
SELECT *
FROM table
WHERE date_colunm
between (
CASE
WHEN DAYOFWEEK(curdate()) > 4
THEN DATE_SUB(NOW(), INTERVAL (7-DAYOFWEEK(curdate())) DAY)
ELSE (
CASE
WHEN DAYOFWEEK(curdate()) < 4
THEN DATE_ADD(NOW(), INTERVAL (4-DAYOFWEEK(curdate())) DAY)
ELSE curdate()
END
)
END
) as date
AND DATE_ADD (
(
CASE
WHEN DAYOFWEEK(curdate()) > 4
THEN DATE_SUB(NOW(), INTERVAL (7-DAYOFWEEK(curdate())) DAY)
ELSE (
CASE
WHEN DAYOFWEEK(curdate()) < 4
THEN DATE_ADD(NOW(), INTERVAL (4-DAYOFWEEK(curdate())) DAY)
ELSE curdate()
END
)
END
) as date, INTERVAL 6 DAY
)
NOTE :
There are some codes for the days like for Wednesday we have 4 (as mentioned in query),
so you can change the code according to your requirements. Like for Monday is : 2

Select data that was added the last 7 days

I have a table where the time is a date type. I would like to select all the records that were added the last 7 days and then out put them in an xml file. I can select all data and output it fine without a WHERE statement.
Here is the code:
$query_feed = "SELECT * FROM keysound_data WHERE time >=DATE_SUB(CURDATE(), INTERVAL 7 DAY AND time <= CURDATE()";
$feed = mysql_query($query_feed, $dconn) or die(mysql_error());
$row_feed = mysql_fetch_assoc($feed);
$totalRows_feed = mysql_num_rows($feed);
echo'<items>';
while ($row_feed = mysql_fetch_assoc($feed)){
echo'
<item>
<name>'.$row_feed['Name'].'</name>
<email>'.$row_feed['email'].'</email>
<date>'.$row_feed['Date'].'</date>
<description>'.$row_feed['Make'].' '.$row_feed['Model'].' '.$row_feed['Type'].'</description>
<logon>'.$row_feed['Logon'].'</logon>
<category>'.$row_feed['Type'].'/'.$row_feed['Make'].'</category>
<product_search_code>'.$row_feed['Product_search_code'].'</product_search_code>
<order_ref>'.$row_feed['Invoice'].'</order_ref>
<product_link>'.$row_feed['Product_link'].'</product_link>
<customer_ref>'.$row_feed['Invoice'].'</customer_ref>
<amount>'.$row_feed['Price'].'</amount>
<currency>GBP</currency>
</item>';
}
echo '</items>';
Not sure what's going wrong. Any help welcome
You're missing a bracket in your SQL to close DATE_SUB function.
Try this:
SELECT *
FROM keysound_data
WHERE
time >=DATE_SUB(CURDATE(), INTERVAL 7 DAY)
AND time <= CURDATE()
Better yet, you could use BETWEEEN to optmize your query:
SELECT *
FROM keysound_data
WHERE
time BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()
EDIT: As #spencer7593 noticed, CURDATE() - INTERVAL 7 DAY should be used instead of DATE_SUB(CURDATE(), INTERVAL 7 DAY) for even better optimization. The query above was updated to make use of that.
You are missing a closing bracket.
Try this-
time >=DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND time <= CURDATE()
SELECT *
FROM keysound_data
WHERE
time BETWEEN (now() - INTERVAL 7 DAY) AND now()

Single query to get count of individual of past 7 days

I do know that the following conditions will return the total number in the past 7 days
SELECT count(id) FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
Is there a single query that I can do to get the past 7 days returning in an array of 7 results of each individual day?
For example:
day 1 - 10
day 2 - 5
day 3 - 9
..
..
..
This will give you the date and the count.
SELECT DATE(createdDate),COUNT(id)
FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
GROUP BY DATE(createdDate)
Alternatively to give a result closer to your example you could use:
SELECT CONCAT("Day ",DATEDIFF(NOW(), createdDate)) AS day,COUNT(id)
FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
GROUP BY DATE(createdDate)
Add a group-by clause:
SELECT count(id), DATE(createdDate)
FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
GROUP BY DATE(createdDate)
select 8 - n day, count(id)
from registration
join (select 1 n union select 2 union select 3 union select 4 union select 5 union select 6 union select 7) x
on createdDate between date_sub(curdate(), interval n day) and date_sub(curdate(), interval n-1 day)
group by day
order by day

Getting sum of duplicated date entries from last month, week, day

I have a table with 3 columns: id, updated_at, click_sum.
Many rows have the exact same updated_at value which makes it hard to simply retrieve the data, order by updated_at and display the sums in a chart.
Since there are multiple sums for the same dates which screws the chart.
What I try to achieve is to get the following output:
update_at | click_sum
-----------+-----------
date1 | 100
date2 | 3
date3 | 235
date4 | 231
Optionally only those dates which are form the last month, week or day AND not simply the dates which are NOW() - 1 month.
The current query I build is very large and doesn't work that well.
It groups by dates (no duplicated dates appear) and SUM()s the clicks correctly but defining from when (last month, week, day) the dates are doesn't seem to work properly.
Query: ($interval stands for MONTH or DAY or SECOND or WEEK)
SELECT d.updated_at, SUM(d.clicks_sum) AS click_sum
FROM aggregated_clicks d
JOIN
(
SELECT c.id, MAX(StartOfChains.updated_at) AS ChainStartTime
FROM aggregated_clicks c
JOIN
(
SELECT DISTINCT a.updated_at
FROM aggregated_clicks a
LEFT JOIN aggregated_clicks b ON (b.updated_at >= a.updated_at - INTERVAL 1 DAY AND b.updated_at < a.updated_at)
WHERE b.updated_at IS NULL
) StartOfChains ON c.updated_at >= StartOfChains.updated_at
GROUP BY c.id
) GroupingQuery
ON d.id = GroupingQuery.id
WHERE GroupingQuery.ChainStartTime >= DATE_SUB(NOW(), INTERVAL 1 $interval)
GROUP BY GroupingQuery.ChainStartTime
ORDER BY GroupingQuery.ChainStartTime ASC
maybe I'm assuming too much about the nature of your question (and the table it refers to), but I think this can be done much more simply than the query you've shown.
figuring the latest completed month isn't very hard.
it starts with knowing the first date of this current month -- use this:
date_sub(curdate(), interval (extract(day from curdate())-1) day)
and to know the first day of that previous month, use this:
date_sub(date_sub(curdate(), interval extract(day from (curdate())-1) day), interval 1 month)
so if you want to get the sums for just the days in between -- i.e. the latest completed month, use this:
select updated_at, sum(click_sum) from aggregated_clicks
where updated_at >= date_sub(date_sub(curdate(), interval extract(day from (curdate())-1) day), interval 1 month)
and updated_at < date_sub(curdate(), interval (extract(day from curdate())-1) day)
group by updated_at;
figuring the lastest completed week is just as easy. this example will assume a Sunday-Saturday week.
because of the way the ODBC standard defines date numbers, it's easy to find the end (Saturday) of the previous week:
date_sub(curdate(), interval dayofweek(curdate()) day)
and the beginning (Sunday) of that week is six days before that:
date_sub(curdate(), interval (dayofweek(curdate())+6) day)
so if you want to get the sums for just the days in between -- i.e. the latest completed week, use this:
select updated_at, sum(click_sum) from aggregated_clicks
where updated_at >= date_sub(curdate(), interval (dayofweek(curdate())+6) day)
and updated_at <= date_sub(curdate(), interval dayofweek(curdate()) day)
group by updated_at;
and of course figuring based on the latest completed day is super easy.
to get the date of the previous day, use this:
date_sub(curdate(), interval 1 day)
so if you want the sums just for yesterday, use this:
select updated_at, sum(click_sum) from aggregated_clicks
where updated_at = date_sub(curdate(), interval 1 day)
group by updated_at;
NOTE: I've tested these queries using MySQL 5.1, YMMV.
----------
UPDATE: since the date column is a datetime, simply change all references to updated_at in my queries to date(updated_at) like so:
month case:
select date(updated_at), sum(click_sum) from aggregated_clicks
where date(updated_at) >= date_sub(date_sub(curdate(), interval extract(day from (curdate())-1) day), interval 1 month)
and date(updated_at) < date_sub(curdate(), interval (extract(day from curdate())-1) day)
group by date(updated_at);
week case:
select date(updated_at), sum(click_sum) from aggregated_clicks
where date(updated_at) >= date_sub(curdate(), interval (dayofweek(curdate())+6) day)
and date(updated_at) <= date_sub(curdate(), interval dayofweek(curdate()) day)
group by date(updated_at);
yesterday case:
select date(updated_at), sum(click_sum) from aggregated_clicks
where date(updated_at) = date_sub(curdate(), interval 1 day)
group by date(updated_at);

Categories