0

我需要排除类似于 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();
}
4

4 回答 4

3

您的 a 语法LEFT JOIN是错误的,它应该是以下形式:

SELECT     room_number
FROM        rooms
LEFT JOIN .... ON ...
WHERE  ...
ORDER BY ...

还是您在寻找 aUNION而不是 a LEFT JOIN

尽管在您的情况下,您可能只是反转第二个查询的条件并将其用作WHERE第一个查询中的条件(如果我理解正确的话......)。

于 2013-07-08T15:08:05.900 回答
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  

使用联接而不是子查询

  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 
于 2013-07-08T15:16:59.187 回答
1

在 MySQL 中,您加入表,而不是 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
于 2013-07-08T15:25:22.383 回答
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");

这是我在我的应用程序中使用的语法

于 2014-11-14T06:55:56.557 回答