左外连接查询

时间:2010-08-25 13:56:57

标签: sql mysql

我有两张桌子,一张用于预订,另一张用于房间分配。预订表有一个id和房间分配表有一个id和room_id(id指的是预订ID)。我想查找房间分配表中没有条目的所有预订清单。

我做了以下查询:

$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我得到一个错误,上面写着:

  

[本机消息:您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在'id WHERE(rbs_room_allocation.id IS NULL)AND(booking.trip_id =?)AND(在第1行预订')附近使用正确的语法

我不知道为什么这不起作用,我已经尝试将id放入查询而不是使用参数,但我得到相同的错误,所以我假设它与我的查询有关。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

试试这个not exists查询:

$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)";

答案 1 :(得分:2)

你需要将using子句的id列放在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)";