after a little bit search in stackoverflow I came up with this query which I wanted, and its like this:
SELECT * FROM workers where TIMESTAMPDIFF(SECOND, last_activity_time, NOW()) >= (60/per_hour*60)
each record is consist of these fields:
id worker_name last_activity_time per_hour
so each worker has a per_hour field that will determined as actions number per hour.
last activity is the last time worker was doing an action.
It will get records that are qualified to run at current time.
so it will determine time interval with 60/per_hour in seconds and selects the records which time passed from their last_activity_time till now is more than this calculated interval.
this works okay, But I want to know two things.
1: is this query a good approach for this problem or its slow?
2: how can I do this query in laravel 5.5 active records or query builder? and also it should return one record at a time.
thanks in advance
i think your query is fine because there were no joins and no subquerires just only condition is there. You can fire raw queries on laravel to -
$workers = DB::select('SELECT * FROM workers where TIMESTAMPDIFF(SECOND, last_activity_time, NOW()) >= (60/per_hour*60)');
// or you can make use of query builder as follows
$workers = DB::table('workers')->whereRaw('TIMESTAMPDIFF(SECOND, last_activity_time, NOW()) >= (60/per_hour*60')->first();
this should work
\DB::table('workers')->whereRaw(...)->first();
https://laravel.com/docs/5.6/queries
1: is this query a good approach for this problem or its slow?
It will depend on how many workers you have, you should try and see
Related
I am working on a school project where I have to make a todo web app. now i have a little problem. I need to get the records that are running out of time (think 20% of the whole task left). now i'm looking for a solution in php or a sql statement with which i can retrieve only those records.
I tried many statements but i cant get one to work.
SELECT * FROM tasks
WHERE user_id='$user_id'
AND '$currentDate' BETWEEN start_date AND end_date
The above one is working with the date but not with time.
So now I need to have a statement or function that only retrieves the tasks that are almost finished. I've added a screenshot of the database and the application to clarify it a bit.
i hope someone could help me. (this is my first time using stackoverflow so sorry if i do something wrong)
First, you should not be munging your query with constants, date or otherwise. So, use now().
Second, combine the date/time into a single column
Third, you seem to want and:
WHERE user_id = ? AND
NOW() >= start_datetime AND
NOW() < end_datetime
If you want to store the date/time in separate columns, then you can combine them:
WHERE user_id = ? AND
NOW() >= ADDTIME(CAST(start_date as DATETIME), start_time) AND
NOW() < ADDTIME(CAST(end_date as DATETIME), end_time)
SELECT SUM(UNIX_TIMESTAMP(end_time) - UNIX_TIMESTAMP(start_time)) as TIMESTAMPDIFF FROM job_timing_logs
This is Mysqli Query
I want to this query as A laravel query
actually i am working on time count like start time, end time, pause time
my table like id ,start_time , end_time.
Thank you for help.
I am not sure how laravelish your query needs to be, but here is my take
DB::table('job_timing_logs')
->select(DB::raw("SUM(UNIX_TIMESTAMP(end_time) - UNIX_TIMESTAMP(start_time)) as TIMESTAMPDIFF"));
Just try this code :
$q = JobTimingLogs::sum('UNIX_TIMESTAMP(end_time) - UNIX_TIMESTAMP(start_time)');
I am working on a PHP and MySQL based application in which I am processing mysql data tables for one week data at a time. All my PHP scripts will run in a particular sequence and process the data in all tables (upto 15 tables) for given week.
Presently I have written the date filter in WHERE clause and application is working fine.
IS there any way by which I can set the week's date range at one place and all the queries are fired in all the tables with given date range.
I want this bcoz my application processes are growing and its hard to manage 20+ pages and 50+ queries written in it.
I am using command line PHP.
Please suggest the technique if any.
Thanks
You could use $_SESSION...
$sql = $db->query("SELECT * FROM table WHERE date BETWEEN '". $_SESSION['range']['from'] ."' AND '". $_SESSION['range']['to'] ."'");
... which will persist for the browser session.
SELECT stuff from your_table
WHERE your_date_field > DATE_ADD(CURDATE(), INTERVAL - 7 DAY);
Run that once a week to get last 7 days, then hack it around to get the exact results you want.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
I'm trying to create a computer reservation system, where user chooses a computer and select the time how long he will be using this PC. In that time other persons can't reserve this pc, I need to find a solution, how to automaticaly delete all rows containing reserved pc's after their time expires. Thank you for the advice.
The common way to handle this is to store an expires_at timestamp on the reservation row. Then your query to find any "open" reservations would have WHERE 'expires_at' < NOW() or something similar.
This is an untested answer, that may only be a suggestion, but I just started looking at these, so am interested in feedback as well. i'm still working through possibilities and drawbacks, but it might well suit your need.
Take a look at MySQL Events, an article about it is here, and official syntax at Mysql Docs.
Per the article:
An event is similar to a trigger. However, rather than running in
response to a data change, events can be scheduled to run any number
of times during a specific period. In effect, it’s a database-only
cron job.
Pondering this, I'd envision a procedure that deleted anything >1hr (if that's the expiration). This procedure would be TRIGGERED on new inserts to get rid of anything expired at that moment, but also in an event to run every 15 minutes or so so that automatic deletes by the trigger aren't dependant on somebody else adding a reservation to trigger that procedure.
If your server is linux, you can use cron jobs to check once a day every reservation dates. If these dates have expired .. modified field reserves to be available.
Normally I would do it this way:
when storing a reservation, store date_from and date_to both of datatype DATETIME
when checking if there is a computer free check for all computers and filter with WHERE '{$my_date}' >= date_to AND '{$my_date}' <= date_from - by this You should be able to get all the PCs that are not reserved within a certain time...
To be complete in the solution, you need to run a CRON job which calls a query to remove all reservations that have a reservation_time + (15 * 60) < unix_timestamp().
I am assuming you have a time that the reservation was placed or started and are using UNIX/Epoch Timestamps.
Instead of doing a expires_now, if you know it will always be a fixed interval ie 15 minutes, you can do:
DELETE FROM reservations WHERE reservation_time + (15 * 60) < unix_timestamp()
Something you could look into is managing cron job's from PHP, http://www.highonphp.com/cron-job-manager.
The above script will, when a reservation is created, insert an entry into /etc/cron.d/ and you could configure it to run at the expected reservation endtime. Then inside the php file which would be executed, you could do:
DELETE FROM reservations WHERE id = :id
I'm creating a calendar that displays a timetable of events for a month. Each day has several parameters that determine if more events can be scheduled for this day (how many staff are available, how many times are available etc).
My database is set up using three tables:
Regular Schedule - this is used to create an array for each day of the week that outlines how many staff are available, what hours they are available etc
Schedule Variations - If there are variations for a date, this overrides the information from the regular schedule array.
Events - Existing events, referenced by the date.
At this stage, the code loops through the days in the month and checks two to three things for each day.
Are there any variations in the schedule (public holiday, shorter hours etc)?
What hours/number of staff are available for this day?
(If staff are available) How many events have already been scheduled for this day?
Step 1 and step 3 require a database query - assuming 30 days a month, that's 60 queries per page view.
I'm worried about how this could scale, for a few users I don't imagine that it would be much of a problem, but if 20 people try and load the page at the same time, then it jumps to 1200 queries...
Any ideas or suggestions on how to do this more efficiently would be greatly appreciated!
Thanks!
I can't think of a good reason you'd need to limit each query to one day. Surely you can just select all the values between a pair of dates.
Similarly, you could use a join to get the number of events scheduled events for a given day.
Then do the loop (for each day) on the array returned by the database query.
Create a table:
t_month (day INT)
INSERT
INTO t_month
VALUES
(1),
(2),
...
(31)
Then query:
SELECT *
FROM t_month, t_schedule
WHERE schedule_date = '2009-03-01' + INTERVAL t_month.day DAY
AND schedule_date < '2009-03-01' + INTERVAL 1 MONTH
AND ...
Instead of 30 queries you get just one with a JOIN.
Other RDBMS's allow you to generate rowsets on the fly, but MySQL doesn't.
You, though, can replace t_month with ugly
SELECT 1 AS month_day
UNION ALL
SELECT 2
UNION ALL
...
SELECT 31
I faced the same sort of issue with http://rosterus.com and we just load most of the data into arrays at the top of the page, and then query the array for the relevant data. Pages loaded 10x faster after that.
So run one or two wide queries that gather all the data you need, choose appropriate keys and store each result into an array. Then access the array instead of the database. PHP is very flexible with array indexing, you can using all sorts of things as keys... or several indexes.