开发者

SQL Select, Match one column but not another

I have two tables in an SQL Server 2008 R2 database, lets call them A and B. They look like this

A
--------------------
GUID     Primary Key
B_GUID   Foreign Key
Value    nvarchar(50)

B
--------------------
GUID     Primary Key
Value    nvarchar(开发者_开发技巧50)

I want to select all rows from A where

  • B_GUID in A matches GUID in B
  • Value in A does not match Value in B

However, I can't figure out the SQL. Any help? :) Thanks


How about:

SELECT A.*
FROM dbo.A
INNER JOIN dbo.B ON A.B_GUID = B.GUID
WHERE
    A.Value <> B.Value

The INNER JOIN matches the two tables together, on equality of those two columns, and the WHERE clause restricts it further to just two rows where that condition applies.


select 
  A.*
from
  A
join
  B on A.B_GUID = B.GUID and A.Value <> B.Value


SELECT * 
FROM A 
LEFT JOIN B
ON A.B_GUID = B.GUID  WHERE A.Value <> B.Value;

This is not tested but should work


Note, there could be a possible drawback on above answers depending upon the situation: Say if you have records as below even though there is a matching record due to other none matching record you will find the output as mismatch.

TABLE 1     
GUID    B_GUID  VALUE
101 201 X
102 201 Y

TABLE2      
GUID    VALUE   
201 Y   
201 X   

One alternate way to solve this is use EXCEPT clause query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜