Mysql for each different result in query, run another query
How do you write a query that executes for each different result in a query? To explain, I run one query to find all the "punch_periods" within a date range:
$search_date = mysql_query("SELECT punch_period
FROM timecards
WHERE emp_id ='1' &&
punch_time BETWEEN '$start' AND '$end'
ORDER BY punch_time");
while($periods = mysql_fetch_array($search_date)) {
// run another query for each different punch_period
}
The result might be 1,1,1,1,2,2开发者_StackOverflow中文版. Instead of running a second query 6 times (for each result), I need to run a second query 2 times (for each DIFFERENT punch_period). It will be something like:
$punches = mysql_query("SELECT * FROM timecards
WHERE emp_id ='1' &&
punch_period = [RESULT FROM 1ST QUERY]");
The reason I'm doing it this way is because I can't search by date alone- someone may clock in at 11:30pm one day and clock out at 1:00am the following "day". By searching by unique punch periods, I can get total hours worked in a "workday" even if it overlaps a true calendar "day".
I fail to see the purpose of the while loop.
You are just pinging the database server.
It be much faster to get all rows in one query using a subselect
SELECT DISTINCT tc.* FROM timecards tc
WHERE tc.emp_id = '1'
AND tc.punch_period IN (SELECT DISTINCT tc2.punch_period
FROM timecards tc2
WHERE tc2.emp_id ='1'
AND tc2.punch_time BETWEEN '$start' AND '$end')
ORDER BY punch_time
Obviously you can simplify this query to:
SELECT DISTINCT tc.* FROM timecards tc
WHERE tc.emp_id = '1'
AND tc.punch_time BETWEEN '$start' AND '$end'
SELECT * is not recommended
Note that SELECT * is considered an anti-pattern and it is better to explicitly name the fields that you want to select.
SELECT tc.id, tc.punch_time, tc.punch_period ....
Mixing &&
and AND
Don't mix &&
and AND
, just use AND the mix is confusing and &&
is not standard SQL IIRC.
You can simply use 'in' operator.
$punches = mysql_query("SELECT * FROM timecards
WHERE emp_id ='1' &&
punch_period in ( RESULT FROM 1ST QUERY)");
精彩评论