简体   繁体   English

带系统时间戳的嵌套SQL查询

[英]Nested SQL query with system timestamp

I am creating a web-application and backend DB for a carsharing venture. 我正在为一个汽车共享企业创建一个Web应用程序和后端数据库。 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注入的影响。

$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. 但是,您可能真的希望延长开始和结束时间,以免预订会很快就开始的汽车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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