i make a php program
this programe show Schedules of channels
in the page of the channel i want to display the current program and the next one ,
in the table of the Schedules i insert the time of the program in cell called " when "
select when from Schedules where channel_id = 13
this is will display the time of all the programms in timestamp
i wanna to output only the current program , and the next one only
sorry for bad english language
I don't have something to test this against, however this query will get all schedules for channel id 13 that are scheduled after or at $time, we order all such results in asc order by when and finally choose first two out of them (which will be the program at $time and the next after this one)
SELECT field1,field2,when FROM Schedules where channel_id = 13 AND
when >= $time ORDER BY when ASC LIMIT 2
Fill in for field1, field2, and $time variable as required.
Assuming when column is of DATETIME type:
( SELECT * FROM Schedules where channel_id = 13 AND when <= NOW() ORDER BY when DESC LIMIT 1 )
UNION
( SELECT * FROM Schedules where channel_id = 13 AND when > NOW() ORDER BY when ASC LIMIT 1 )
Related
I use MariaDB and have a table where each row has a date and a score.
I want to first show the rows where the date is 3 days old or newer, sorted by the score - then show the rest (more than 3 days old) sorted by date.
Since my date is stored in unix time, it's fairly easy to have php calculate 3 days from before now and use that as my $scoreTimeLimit variable in the below:
Here are my two queries:
SELECT * FROM myTable WHERE myDate > $scoreTimeLimit ORDER BY myPopularityScore DESC
SELECT * FROM myTable WHERE myDate < $scoreTimeLimit ORDER BY myDate DESC
However, I would VERY much like to have only 1 query instead of two. Can it be done...?
This is a job for UNION.
SELECT * FROM (
SELECT 0 ord1, NOW() as ord2, *
FROM myTable WHERE myDate > NOW() - INTERVAL 3 DAY
UNION ALL
SELECT 1 ord1, myDate as ord2, *
FROM myTable WHERE myDate <= NOW() - INTERVAL 3 DAY
) a
ORDER BY ord1, ord2 DESC, myPopularityScore
The inner query gives you a single result set with a couple of extra columns added on to help you manage your sorting.
I have a table that stores shift records for employees.
Simply, there's the following data:
id = Shift ID
employeenum = Employee Number
start = unix timestamp of shift start time
end = unix timestamp of shift end time
date = YYYY-mm-dd description of date the shift starts on
status = shift status (numeric status identifier)
I am currently determining conflicts through a looping php script but it's far too slow. I've searched other questions and can't quite find the answer I'm looking for.
I am trying to come up with a query that will basically give me a list of employeenums that have conflicting shifts within a given time period.
i.e. for the period 2016-07-03 to 2016-07-10, which employees have overlapping start and end timestamps for shifts with a status value of 1 or 7.
Any help would be appreciated.
Thank you!
EDIT
This is essentially the table structure.
id is a primary auto increment key. The table is full of numeric data.
ID is an autoincremented number, employeenum is a 6 digit number, start and end are unix timetamps, date is YYYY-mm-dd date format, overridden is 1 or 0, status is 1,2,3,4,5,6, or 7.
Current loop works by querying:
SELECT * FROM schedule WHERE overridden =0 AND date >=$startdate AND date <= $enddate AND (status = 1 OR status = 7) AND employeenum != 0 ORDER BY date ASC
It then loops through all of those returned shifts to test whether or not another one conflicts with them by executing this query over and over (using the returned start and end values from the results of the above query):
SELECT `employeenum` FROM `schedule` WHERE `overridden` =0 AND `date` >= '$startdate' AND `date` <= '$enddate' AND (`status` = '1' OR `status` = '7') AND ((('$start' > `start`) AND ('$start' < `end`)) OR ((`end` > '$start') AND (`end` < '$end'))) AND `employeenum` = '$employee';"
If there is a result, it pushes the employee number to an array of employees with conflicts. This then prevents the loop from checking for that employee again.
At any given time there could be 10,000 records, so it's executing 10,000+ queries. These records represent only 100-200 employees, so I am looking for a way to query one time to see if there are any overlapping (start and end overlap with another start or end) records between two date values for one employeenum without having to query the database 10,000 times.
This Query will give you the shift id, the date, the employee number, the conflicting employee numbers and a count of conflicting shifts. You have a ton of shifts that conflict in your dataset!!!
SELECT `schedule_test`.`id`, `schedule_test`.`date`, `schedule_test`.`employeenum`, GROUP_CONCAT(DISTINCT`join_tbl`.`employeenum`), COUNT(`join_tbl`.`employeenum`)
FROM `schedule_test`
INNER JOIN `schedule_test` AS `join_tbl` ON
`schedule_test`.`date` = `join_tbl`.`date`
AND (`join_tbl`.`status` = 1 OR `join_tbl`.`status` = 7)
AND (`join_tbl`.`start` BETWEEN `schedule_test`.`start` AND `schedule_test`.`end`
OR `join_tbl`.`end` BETWEEN `schedule_test`.`start` AND `schedule_test`.`end`)
AND `schedule_test`.`id` != `join_tbl`.`id`
WHERE (`schedule_test`.`status` = 1 OR `schedule_test`.`status` = 7)
GROUP BY `schedule_test`.`id`
ORDER BY `schedule_test`.`date`
Adapted from #cmorrissey 's answer. THANK YOU!!
SELECT `schedule_test`.`id`, `schedule_test`.`date`,
`schedule_test`.`employeenum`,
GROUP_CONCAT(DISTINCT`join_tbl`.`employeenum`),
COUNT(`join_tbl`.`employeenum`)
FROM `schedule_test`
INNER JOIN `schedule_test` AS `join_tbl` ON
`schedule_test`.`date` = `join_tbl`.`date`
AND (`join_tbl`.`status` = 1 OR `join_tbl`.`status` = 7)
AND (`join_tbl`.`employeenum` = `schedule_test`.`employeenum`)
AND (`join_tbl`.`start` BETWEEN `schedule_test`.`start` AND `schedule_test`.`end`
OR `join_tbl`.`end` BETWEEN `schedule_test`.`start` AND `schedule_test`.`end`)
AND `schedule_test`.`id` != `join_tbl`.`id`
WHERE (`schedule_test`.`status` = 1 OR `schedule_test`.`status` = 7)
GROUP BY `schedule_test`.`id`
ORDER BY `schedule_test`.`date`
I have a table in database which has the following columns
id, timestamp,user_id
I want to pass two dates and it should find the sum of the records. for example i pass from = 01-12-2014 and 15-12-2014 and it should show a record like
00-04 5
04-08 40
08-12 30
12-16 20
16-20 32
20-24 50
you should group by date and count or sum after your records column something like : "select sum(records) from db_table group by added_date"
For every distinct date he will add/count ( depends on what you want ) the records.
i used a loop to increase time by 14400 and the query is following
select count(id) as sessions from user_history where date_format(login_timestamp, '%d-%m-%Y') < date_format(FROM_UNIXTIME(1157065200), '%d-%m-%Y') and date(login_timestamp) > date_format(FROM_UNIXTIME(1157079600), '%d-%m-%Y') and date_format(login_timestamp, '%H:%i:%s') <= date_format(FROM_UNIXTIME(1157065200), '%H:%i:%s')
I currently have a system to track inventory items.
The sql table is set up as follows:
Unique ID | Order number | Location | TimeStamp
Every time an order moves, a new entry is created with the same order number with the new location and timestamp.
Now I need to find the average time required for order to move from one location to another, say from Location Warehouse to Pickup Depot.
I am trying to work on the query and I have this so far.
SELECT
IFNULL(TIMESTAMPDIFF(SECOND,
MIN(TimeStamp),
MAX(TimeStamp)) / NULLIF(COUNT(*) - 1, 0), 0)
FROM TableName
WHERE Status = 'Delivered'
AND TimeStamp > DATE_SUB(NOW(), INTERVAL 6 HOUR)
The works really well if the table only had one order number, the moment we add more table numbers the average goes off.
I need it to only look at the timestamp difference for each order number, while currently I think its looking at the whole table.
Any help would be much appreciated.
Apologize for posting this question twice, the previous post did not contain enough information.
Thanks again.
SELECT
IFNULL(TIMESTAMPDIFF(SECOND,
MIN(TimeStamp),
MAX(TimeStamp)) / NULLIF(COUNT(*) - 1, 0), 0)
FROM TableName
WHERE Status = 'Delivered'
AND TimeStamp > DATE_SUB(NOW(), INTERVAL 6 HOUR)
GROUP BY OrderNumber
The above query returns the timedifference in different rows in sql (with the following error " Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available.". The table has one column named "IFNULL(TIMESTAMPDIFF(SECOND, MIN(TimeStamp), MAX(TimeStamp)) / NULLIF(COUNT(*) - 1, 0), 0)" with the time difference for various orders arrange in rows. Now I am trying to get their average with the output code.
Am outputting the results with the following code:
$row_cnt = $result2->num_rows;
while ($row2 = mysqli_fetch_assoc($result2)) {
$processingseconds = $row2['IFNULL(TIMESTAMPDIFF(SECOND, MIN(TimeStamp), MAX(TimeStamp)) / NULLIF(COUNT(*) - 1, 0), 0)'] + $processingseconds;
}
print "Current Processing Time: ";
$processingseconds = $processingseconds/$row_cnt;
$processingminutes = $processingseconds/60;
echo $processingminutes;
Try adding a Group by condition to your query.
GROUP BY Order_Number_column
Something like this:
SELECT
IFNULL(TIMESTAMPDIFF(SECOND,
MIN(TimeStamp),
MAX(TimeStamp)) / NULLIF(COUNT(*) - 1, 0), 0)
FROM TableName
WHERE Status = 'Delivered'
AND TimeStamp > DATE_SUB(NOW(), INTERVAL 6 HOUR)
GROUP BY Your_Order_Number_column
I am trying to combine two MYSQL Queries into one. What I want to do is select the first and last row added for each day and subtract the last column for that day from the first column of that day and output that. What this would do is give me a net gain of XP in this game for that day.
Below are my two queries, their only difference is ordering the date by DESC vs ASC. the column in the database that i want to subtract from each other is "xp"
$query = mysql_query("
SELECT * FROM (SELECT * FROM skills WHERE
userID='$checkID' AND
skill = '$skill' AND
date >= ".$date."
ORDER BY date DESC) as temp
GROUP BY from_unixtime(date, '%Y%m%d')
");
$query2 = mysql_query("
SELECT * FROM (SELECT * FROM skills WHERE
userID='$checkID' AND
skill = '$skill' AND
date >= ".$date."
ORDER BY date DESC) as temp
GROUP BY from_unixtime(date, '%Y%m%d')
");
SELECT FROM_UNIXTIME(date, '%Y%m%d') AS YYYYMMDD, MAX(xp)-MIN(xp) AS xp_gain
FROM skills
WHERE userID = '$checkID'
AND skill = '$skill'
AND date >= $date
GROUP BY YYYYMMDD
This assumes that XP always increases, so it doesn't need to use the times to find the beginning and ending values.
If that's not a correct assumption, what you want is something like this:
SELECT first.YYYYMMDD, last.xp - first.xp
FROM (subquery1) AS first
JOIN (subquery2) AS last
ON first.YYYYMMDD = last.YYYYMMDD
Replace subquery1 with a query that returns the first row of each day, and subquery2 with a query that returns the last row of each day. The queries you posted in your question don't do this, but there are many SO questions you can find that explain how to get the highest or lowest row per group.