admin

SQL查询可根据用户输入查找匹配值

sql

我正在为房地产经纪人和租户建立一个网站。租户可以注册并填写所需的物业位置,包括街道,城镇和邮政编码。一旦他们注册,它会自动通过电子邮件发送具有与那些搜索条件匹配的属性的代理。

目前,我将查询设置如下,以使其与街道,城镇或邮政编码匹配。

<%
Dim rspropertyresults
Dim rspropertyresults_numRows

Set rspropertyresults = Server.CreateObject("ADODB.Recordset")
rspropertyresults.ActiveConnection = MM_dbconn_STRING
rspropertyresults.Source = "SELECT * FROM VWTenantPropertiesResults "

'WHERE     (ContentStreet = 'Holderness Road') OR (ContentTown = 'Hull') OR (ContentPostCode = 'HU')

rspropertyresults.Source = rspropertyresults.Source& "WHERE (ContentStreet = '" & Replace(rspropertyresults__varReqStreet, "'", "''") & "'"

rspropertyresults.Source = rspropertyresults.Source& "OR ContentTown = '" & Replace(rspropertyresults__varReqTown, "'", "''") & "' "
rspropertyresults.Source = rspropertyresults.Source& "OR ContentTrimmedPostCode = '" & Replace(varPostcode, "'", "''") & "' ) "

rspropertyresults.Source = rspropertyresults.Source& "AND (( ContentBedRooms >= " & Replace(rspropertyresults__varBedroomsNoMin, "'", "''") & " "
rspropertyresults.Source = rspropertyresults.Source& "AND ContentBedRooms <= " & Replace(rspropertyresults__varBedroomsNoMax, "'", "''") & " ) "

rspropertyresults.Source = rspropertyresults.Source& "AND ( ContentPrice > = " & Replace(rspropertyresults__varPriceMin, "'", "''") & " "
rspropertyresults.Source = rspropertyresults.Source& "AND ContentPrice <= " & Replace(rspropertyresults__varPriceMax, "'", "''") & " )) " & varSQL & " "

rspropertyresults.Source = rspropertyresults.Source& "ORDER BY ContentPrice " & Replace(rspropertyresults__varSortWay, "'", "''") & " "

rspropertyresults.CursorType = 0
rspropertyresults.CursorLocation = 2
rspropertyresults.LockType = 1
rspropertyresults.Open()

rspropertyresults_numRows = 0
%>

但是,客户要求的是,不仅要匹配一个值,还需要以某种方式工作:如果说“街道”和“城镇”匹配,则通过电子邮件将该物业代​​理发送给您,或者如果“城镇”和“邮政编码”匹配,然后通过电子邮件将该物业代​​理发送给您。

您可以想象,我认为查询将变得非常复杂,但是我不确定如何最好地设计这样的查询。

我想知道是否有人可以提供帮助或为我指明正确的方向?


阅读 347

收藏
2021-07-01

共1个答案

admin

SELECT  *
FROM    (
        SELECT  id
        FROM    (
                SELECT  id
                FROM    VWTenantPropertiesResults
                WHERE   ContentStreet = 'Holderness Road'
                UNION ALL
                SELECT  id
                FROM    VWTenantPropertiesResults
                WHERE   ContentTown = 'Hull'
                UNION ALL
                SELECT  id
                FROM    VWTenantPropertiesResults
                WHERE   ContentPostCode = 'HU'
                ) qi
        GROUP BY
                id
        HAVING  COUNT(*) >= 2
        ) q
JOIN    VWTenantPropertiesResults r
ON      r.id = q.id
WHERE   ContentBedrooms BETWEEN 1 AND 4
        AND ContentPrice BETWEEN 50 AND 500
ORDER BY
        ContentPrice

这将返回至少2符合条件的所有记录。

该解决方案是指数型:不同OR的条款,它将使用上的索引ContentStreetContentTownContentPostCode

有关性能的详细信息,请参见我的博客中的以下条目:

为了获得最佳性能和安全性,请使用绑定参数替换替换的参数值。

这将节省您解析查询的时间,并可以防止SQL注入。

2021-07-01