简体   繁体   中英

Nested SQL query with system timestamp

I am creating a web-application and backend DB for a carsharing venture. I want to ensure that only search results for cars that are not reserved as of the current time are shown. I've typed up a query (below) but I am unsure if it is correct. I am using two relations, Reservations and Cars.

Reservations(R_No, M_ID, VIN, A_Code, start_time, end_time)
Cars(VIN, make, model, year, P_address, r_fee)

Is this a valid query? If not, what would make it valid?

$sql = "SELECT make, model, year, P_address, r_fee, VIN 
                    FROM `Cars`, `Reservations`
                    WHERE (
                            (make LIKE %'$search'% ) or
                            (model LIKE %'$search'%) or
                            (year LIKE %'$search'%) or
                            (P_address LIKE %'$search'%) or
                            (r_fee LIKE %'$search'%) and
            (Cars.VIN != Reservations.VIN)
        AND (
            SELECT start_time, end_time
            FROM   Reservations
            WHERE  end_time <= SYSDATETIME() <= start_time));"

This should be modified to use a parameterized query, and would be subject to SQL injection.

$sql = "SELECT c.`make`, c.`model`, c.`year`, c.`P_address`, c.`r_fee`, c.`VIN`
    FROM `Cars` c
    LEFT JOIN `Reservations` r
    ON c.`VIN` = r.`VIN` AND TIMESTAMP BETWEEN r.`end_time` AND r.`start_time`
    WHERE (
            (c.`make` LIKE '%$search%' ) or
            (c.`model` LIKE '%$search%') or
            (c.`year` LIKE '%$search%') or
            (c.`P_address` LIKE '%$search%') or
            (c.`r_fee` LIKE '%$search%')
        )
        AND r.`id` IS NULL;";

This will return a list of cars that do not have a reservation currently. However, you probably really want to extend the start and end time period so you don't get cars that have a reservation that starts very soon.

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