【问题标题】:How make the query in SQL Server which compare the data in data base如何在 SQL Server 中查询比较数据库中的数据
【发布时间】:2023-03-23 12:20:01
【问题描述】:

在我的数据库中会有一个“首选位置”字段,其中包含城市名称,例如“艾哈迈达巴德、阿南德、巴罗达”

在雇主部分,当雇主输入位置“Anand”时,将选择上述记录。
如何进行查询以搜索城市 Ahmadabad 的所有城市,并在搜索时显示此记录

【问题讨论】:

    标签: asp.net sql-server sql-server-2005


    【解决方案1】:

    正确的答案是您需要稍微规范一下您的 SQL 架构。您需要三个单独的表:customer、locations 和 customer_locations。位置表每个城市有一条记录,至少有两列:city_id 和 name。 customer_locations 表正好有两列:customer_id 和city_id。这称为“查找”表,允许您定义“多对多”关系。

    现在您的查询会稍微复杂一些,因为您必须使用“join”。但复杂性带来了灵活性 - 您的搜索将是准确的,并且您将避免出现诸如城市名称意外拼写错误的记录(最终不会匹配)等问题。

    我确定您需要进行更多研究,但您的查询将类似于:

    select cust.*, city.* from customers cust inner join customer_locations cl on
    cust.customer_id = cl.customer_id inner join locations city on cl.city_id = city.city_id
    where city.name = 'Anand';
    

    【讨论】:

      【解决方案2】:

      最容易使用的'LIKE'

      例如:

      select *
      from MyTable
      where Location like '%Ahmadabad%'
      

      但是,这也会找到像“新艾哈迈达巴德”这样的城市。不知道你是否可以忽略。

      如果你不能忽视,你可以这样做:

      select *
      from MyTable
      where 
          Location like '%,Ahmadabad,%' or 
          Location like 'Ahmadabad,%' or
          Location like '%,Ahmadabad'
      

      【讨论】:

      • 如果我没记错的话,我应该使用 charIndex 而不是 %...% 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 2011-05-30
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      相关资源
      最近更新 更多