如何匹配属于2个不同表的这些记录

时间:2018-06-19 11:05:35

标签: sql-server where

我有2个表(2008 mssql数据库),比方说x.dbo和y.dbo

x.dbo有一个名为“customer name”的字段名称,y.dbo有一个名为“customers”的字段名称..我想要的是过滤匹配所有部分匹配的的客户..(其中2个条件)

这是我的查询: 选择x.customernameASAlıcı,y.customers FROM y cross JOIN x 哪里(x.AlıcıLIKE'%'+客户+'%')

上面的查询给出了一些匹配的记录,但不是全部。

举个例子,查询成功找到了这条记录:

CUSTOMER NAME   CUSTOMERS
BARKIN KULA     barkın kula

但不给出这个:

CUSTOMER NAME   CUSTOMERS
KÜBRA ÇALIŞKAN  Kybele Global Kübra Çalışkan

虽然这两个字段都包含“kübraçalışkan”..

但另一方面; 它发现这个与上面的“kübraçalışkan”示例非常相似:

CUSTOMER NAME                               CUSTOMERS
KVK TEKNOLOJİ ÜRÜNLERİ VE TİC.A.Ş.-MERKEZ   kvk teknoloji ürünleri

因此我不确定为什么我的查询对某些记录有效,而对其他记录无效。

2 个答案:

答案 0 :(得分:0)

You should use the LIKE-mathing both ways:

WHERE x.customername LIKE '%' + y.customers    + '%'
OR    y.customers    LIKE '%' + x.customername + '%'

This assumes that your collation is set to a "CI"-variant (Case Insensitive). If you are using a "CS"-variant (Case Sensitive) then you can add UPPER(...) or LOWER(...) on all column names in the query, or specify COLLATE with a CI-variant such as in this example:

WHERE x.customername LIKE '%' + y.customers    + '%' COLLATE SQL_Latin1_General_CP1_CI_AS
OR    y.customers    LIKE '%' + x.customername + '%' COLLATE SQL_Latin1_General_CP1_CI_AS

答案 1 :(得分:0)

尝试这个:

CREATE TABLE X(
    CustomerName NVARCHAR(45)
    );

CREATE TABLE Y(
    Customers NVARCHAR(45)
    );

INSERT INTO X VALUES
(N'BARKIN KULA'),
(N'KÜBRA ÇALIŞKAN');

INSERT INTO Y VALUES
(N'barkın kula'),
(N'Kybele Global Kübra Çalışkan');

SELECT *
FROM X JOIN Y ON
UPPER(X.CustomerName) LIKE '%' + UPPER(Y.Customers)    + '%'
OR    UPPER(Y.Customers)    LIKE '%' + UPPER(X.CustomerName) + '%';

结果:

+----+----------------+------------------------------+
|    |  CustomerName  |          Customers           |
+----+----------------+------------------------------+
|  1 | BARKIN KULA    | barkın kula                  |
|  2 | KÜBRA ÇALIŞKAN | Kybele Global Kübra Çalışkan |
+----+----------------+------------------------------+

这意味着您拥有Case sensitive collation,类似于Latin1_General_CS_AS(其中CS = Case sensitive),您也可以考虑对其进行更改。

您可以运行以下查询以查看数据库的排序规则:

SELECT name, collation_name 
FROM sys.databases
WHERE name = 'YourDatabaseName';

要更改数据库的排序规则,只需运行查询:

ALTER DATABASE YourDatabaseName
   COLLATE Collation;

要查看可用的归类,然后选择正确的归类:

SELECT * FROM ::fn_helpcollations();