简体   繁体   English

mysql查询来搜索地址或邮政编码

[英]mysql query to search for address or postcode

Hi I am having difficulties writing a perfect sql query that will search for an address or postcode(english). 嗨,我在编写完善的sql查询以查找地址或邮政编码(英语)时遇到困难。

I stored my postcode as "W1Y TF7". 我将邮政编码存储为“ W1Y TF7”。 If a user searches using "W1YTF7" (without the space), it does give me any result when it is suppose to return W1Y TF7. 如果用户使用“ W1YTF7”(不带空格)进行搜索,那么在假定要返回W1Y TF7时,它确实会给我任何结果。

VENUE VENUE

  • VenueID VenueID
  • Name 名称
  • Address1 地址1
  • Address2 地址2
  • City
  • Postcode 邮编
  • PhoneNumer PhoneNumer
  • URL 网址

here is my query: 这是我的查询:

SELECT DISTINCT *
 FROM venue 
WHERE Name LIKE '%$searchValue%' 
   OR Postcode LIKE '%$searchValue%'
   OR Address2 LIKE '%$searchValue%' 
   OR Postcode LIKE '$searchValue%' 

I would probably store the postcodes in the database without the space. 我可能会在没有空间的情况下将邮政编码存储在数据库中。 Then you could simply strip the spaces out of the string before running your SQL query. 然后,您可以在运行SQL查询之前简单地从字符串中去除空格。

If you want to keep your current setup, why not convert the input into your expected format BEFORE it gets to the SQL level? 如果要保留当前设置,为什么不在输入到SQL级别之前将其转换为期望的格式? Just add the space if it's not there. 如果不存在,只需添加空间即可。

well, the first pitfall: I could see you run into some problems here if things are uninitiated (if $searchValue is an empty string or a very small string). 好吧,这是第一个陷阱:如果事情没有开始,我会看到您在这里遇到了一些问题(如果$ searchValue是一个空字符串或非常小的字符串)。 This would always return a very large dataset (and might take quite some time). 这将始终返回非常大的数据集(可能会花费一些时间)。

for the postcode, you could do (LEFT(Postcode, 3) = LEFT($searchValue, 3) AND RIGHT(Postcode, 3) = RIGHT($searchValue, 3)) 对于邮政编码,您可以这样做(LEFT(Postcode, 3) = LEFT($searchValue, 3) AND RIGHT(Postcode, 3) = RIGHT($searchValue, 3))

also, you might want to look into prepared statements and value binding, but that's a different problem altogether 另外,您可能希望研究准备好的语句和值绑定,但这完全是另一个问题

You can make a search column, create a new field that you call SearchColumn the venue table, then make a SELECT and UPDATE trigger that sets the same values in all the fields you want to use (VenueID + Name + Address1 + Address2 + City + Postal Code + PhoneNumer + URL). 您可以创建一个搜索列,在场所表中创建一个名为SearchColumn的新字段,然后创建一个SELECT和UPDATE 触发器 ,以在要使用的所有字段中设置相同的值(地点ID +名称+地址1 +地址2 +城市+邮政编码+电话号码+ URL)。 ex. 恩。 if you insert. 如果您插入。 It's also nice to have this included as an index . 将其作为索引包含也很好。

Then you need to: 然后,您需要:

SELECT DISTINCT Name
      FROM venue
       WHERE SearchColumn LIKE '%Search value%'

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

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