简体   繁体   中英

Left Outer Join Query

I have two tables, one for bookings and one 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)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM