开发者

Left Outer Join Query

I have two tables, one for bookings and on开发者_如何学JAVAe for room allocations. Booking table has an id and room allocations table has an id and room_id (id refers to the booking id). I want to find a list of all of the bookings who do not have an entry in the room allocations table.

I made the following query:

$sql = "SELECT booking.id, booking.username, booking.contact_name 
FROM booking LEFT OUTER JOIN rbs_room_allocation 
USING id 
WHERE (rbs_room_allocation.id IS NULL) 
AND (booking.trip_id = :trip_id) 
AND (booking.paid = booking.total)";

$params = array('trip_id' => $trip_id);
$result = $dbh->getAll($sql, null, $params);

Buut I get an error which says:

[Native message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'id WHERE (rbs_room_allocation.id IS NULL) AND (booking.trip_id = ?) AND (booking' at line 1]

I have no idea why this isn't working, I've tried putting an id into the query instead of using parameters but I get the same error so I'm assuming it's something to do with my query. Any help is much appreciated!


Try this not exists query:

$sql = "SELECT b.id, b.username, b.contact_name 
FROM booking b
WHERE 
b.trip_id = :trip_id
and b.paid = b.total
AND NOT EXISTS (select 1 from rbs_room_allocation where id = b.id)";


you need to put the id column for the using clause inside parens:

$sql = "SELECT booking.id, booking.username, booking.contact_name 
FROM booking LEFT OUTER JOIN rbs_room_allocation 
USING (id) 
WHERE (rbs_room_allocation.id IS NULL) 
AND (booking.trip_id = :trip_id) 
AND (booking.paid = booking.total)";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜