我需要排除第二个查询(来自第二个表的数据),类似于MINUS。但由于MySQL不支持MINUS,我决定选择LEFT JOIN。但它给我一个数据库错误。
模型
function searchRooms($room_type, $start_date, $end_date) {
// Line 6 is the below one:
$query = $this->db->query(
"SELECT room_number
FROM rooms
WHERE room_type = '$room_type'
ORDER BY room_number ASC
LEFT JOIN
SELECT room_number
FROM new_reservation
WHERE start_date >= '$start_date'
AND end_date <= '$end_date'
ORDER BY room_number ASC
");
return $query->result();
}
控制器
function search() {
$room_type = $this->input->post('room_type');
$start_date = $this->input->post('start_date');
$end_date = $this->input->post('end_date');
$this->reservations_model->searchRooms($room_type, $start_date, $end_date);
$this->index();
}
答案 0 :(得分:3)
LEFT JOIN
的语法错误,应该是以下形式:
SELECT room_number
FROM rooms
LEFT JOIN .... ON ...
WHERE ...
ORDER BY ...
或者您在寻找UNION
而不是LEFT JOIN
?
虽然在你的情况下你可能只是反转第二个查询的条件,并在第一个查询中将其用作WHERE
条件(如果我理解正确的话......)。
答案 1 :(得分:2)
如果要从第二个查询中排除结果,那么
SELECT room_number
FROM rooms
WHERE room_type = '$room_type'
AND room_number not in (SELECT room_number
FROM new_reservation
WHERE start_date >= '$start_date'
AND end_date <= '$end_date')
ORDER BY room_number ASC
使用join而不是子查询
SELECT a.room_number
FROM rooms a left outer join (SELECT room_number
FROM new_reservation
WHERE start_date >= '$start_date'
AND end_date <= '$end_date') b
ON a.room_number = b.room_number
WHERE a.room_type = '$room_type'
AND b.room_number is null
ORDER BY a.room_number ASC
如果您不想使用内嵌视图,请再次
SELECT a.room_number
FROM rooms a left outer join new_reservation b
ON a.room_number = b.room_number
WHERE a.room_type = '$room_type'
AND b.start_date >= '$start_date'
AND b.end_date <= '$end_date'
AND b.room_number is null
ORDER BY a.room_number ASC
答案 2 :(得分:1)
在MySQL中,您是JOIN表,而不是SELECT语句。当JOINed表中可能没有匹配的行时,使用LEFT JOIN。
您想要加入并仅选择所需的行。
试试这个:
SELECT rooms.room_number
FROM rooms
JOIN new_reservation ON rooms.room_number = new_reservation.room_number
WHERE rooms.room_type = '$room_type'
AND NOT (start_date >= '$start_date' AND end_date <= '$end_date')
ORDER BY room_number ASC
答案 3 :(得分:0)
在codeigniter中你可以像这样使用
$this->db->query("select tb.required_field,tb.another_require_field from table_name as tb
left join another_table_name as atb on atb.common_column = tb.common_column
where tb.conditional_colun= condition");
这是我在我的应用程序中使用的语法