I have this query, which is made from snippets/ideas around here - I am not an expert in the more advanced SQL yet. The part I want you to focus on is: WHERE ... l.status='active'
SELECT l.*, COUNT(c.id) AS callsNum
FROM leads AS l
LEFT JOIN calls AS c ON c.lead = l.id
WHERE l.pool IN ($pools) AND l.status='active' AND l.center='$center'
GROUP BY l.id
ORDER BY callsNum ASC, l.id ASC
LIMIT 0,1
I can't get the error myself, but some people has experienced errors where leads with a status that is not "active" has come up.
Can anyone spot the error? I suppose the code can be better too, any suggestions are welcome - if it ain't clear what the code is supposed to do, feel free to ask.
UPDATE:
Thanks for all your responses. I'm glad you think the query should work. I suppose I need to add some more info.
The system is for a small callcenter. The query is getting the next lead from the selected pools, that the caller should call to. In the same AJAX call to the PHP file the "next lead" gets marked as "processing" to avoid multiple callers getting the samme lead.
As pointed out the problem could technically happen if two callers pressed the "get next lead" button on the exact same time. But they have reported to me, that even if they are just 2 callers calling on the same pools at the same time, they get the same lead quite often. If they are 4 callers, even more often.
I therefore put in some lines of code just after this query, that checks one more time that the lead has status='active' - and if not, it comes up with an error (to prevent multiple callers calling at the same time). This error comes quite often, and I therefore suspect that something is wrong with this query.
It is very important that a lead won't come up multiple times. Any suggestions?
RELEVANT CODE (FULL)
Here is a longer code example as requested. The error in the end comes up quite often with just 2-4 persons using it (on a quite fast server).
// Get next lead
$stmt = $db->prepare("
SELECT l.*, COUNT(c.id) AS callsNum
FROM leads AS l
LEFT JOIN calls AS c ON c.lead = l.id
WHERE l.pool IN ($pools) AND l.status='active' AND l.center='$center'
GROUP BY l.id
ORDER BY callsNum ASC, l.id ASC
LIMIT 0,1");
$stmt->execute();
$res = $stmt->get_result();
if($res->num_rows > 0) {
while($row = $res->fetch_assoc()) {
// Set as "processing" to avoid simultaneous call from multiple bookers
$stmt = $db->prepare("UPDATE leads SET status='processing' WHERE status='active' AND id=? AND center='$center'");
$stmt->bind_param("i", $row["id"]);
$stmt->execute();
$affectedRows = $stmt->affected_rows;
if($affectedRows != 1) {
echo 'ERROR. Please reload.';
die;
}
}
}