我有mysql查询
var query = "SELECT * FROM drivers WHERE status = 1 AND lat BETWEEN " + min_lat + " AND " + max_lat + " AND lng BETWEEN " + min_lon + " AND " + max_lon + " AND isAvailable = 1 LIMIT 1";
我想再增加一个条件。假设我有一个名为
的表booking
driverId bookingStatus
现在我想让所有带有上述查询的驱动程序+条件,预订表行数应为0,其中bookingStatus小于3,driverId存在于预订表中
答案 0 :(得分:1)
左边加入预订上的驱动程序表,并在连接条件中过滤bookingstatus字段上的预订。如果预订表中没有与条件匹配的行,那么结果集中预订表中的driverid将为null。
SELECT d.*
FROM drivers d
LEFT JOIN booking b ON d.driverid=b.driverid and b.bookingStatus<3
WHERE d.status = 1 AND d.lat BETWEEN ... AND ...
AND d.lng BETWEEN ... AND ...
AND d.isAvailable = 1
AND b.driverid is null
LIMIT 1
如果您特别需要检查预订表中是否存在驱动程序,则将exists子查询添加到where条件。