简体   繁体   English

比较具有不同值的两个表

[英]Comparing two tables with different values

I have two tables each in different DB on the same server...with multiple columns in SQL.我在同一服务器上的不同数据库中有两个表......在 SQL 中有多个列。

I need to fetch the records where the value of one of the column I use is present in TableA and not in TableB.我需要获取我使用的列之一的值出现在 TableA 中而不是在 TableB 中的记录。 This column is alphanumeric (BIGINT) in TableA while it is different in TableB it is ShortDescription(varchar(100))此列在 TableA 中是字母数字 (BIGINT),而在 TableB 中是不同的,它是 ShortDescription(varchar(100))

TableB column's value is ONLY numbers same as Table A column but without characters (for example 123) while TableA column value can contain for example "ab123" TableB 列的值仅是与 Table A 列相同但没有字符(例如 123)的数字,而 TableA 列值可以包含例如“ab123”

Now if value "abc123" in TableA is present in Table A and value "123" is not in Table B, then I should get that record from table A. If 123 is present in Table B for that column, then I shouldn't fetch.现在,如果表 A 中的值“abc123”出现在表 A 中,而值“123”不在表 B 中,那么我应该从表 A 中获取该记录。如果表 B 中的该列存在 123,那么我不应该拿来。

How to do?怎么做?

Try this query.试试这个查询。 It makes things simple by joining the two tables, then utilizing the WHERE clause.通过连接两个表,然后使用WHERE子句,它使事情变得简单。 I'll just call the common column between the two tables "Id" for the join:我将只调用两个表之间的公共列“Id”来进行连接:

SELECT * FROM TableA 
LEFT JOIN TableB ON TableA.Id = TableB.Id 
WHERE TableA.Column1 = "ab123" AND TableB.ShortDescription != "123";

You need PATINDEX to find the numbers from TableA.Column1 and then match it with TableB.Column2.您需要 PATINDEX 从 TableA.Column1 中查找数字,然后将其与 TableB.Column2 匹配。 Below is the query for you:以下为您查询:

Select Column1 FROM TableA WHERE EXISTS (SELECT 1 FROM TableB WHERE SUBSTRING(CAST(Column1 AS VARCHAR), PATINDEX('%[0-9]%', CAST(Column1 AS VARCHAR)), LEN(Column1))=Column2) Select 列 1 从表 A 中存在(从表 B 中选择 1,其中子字符串(CAST(列 1 作为 VARCHAR),PATINDEX('%[0-9]%',CAST(列 1 作为 VARCHAR)),LEN(列 1))=列 2)

I am assuming you do not have a common column between two tables.我假设您在两个表之间没有公共列。 Otherwise you can use the common column to join and put the PATINDEX statement in WHERE clause.否则,您可以使用公共列连接并将 PATINDEX 语句放在 WHERE 子句中。

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

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