Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 210
Fredrik Hedblad Avatar asked Jan 21 '23 02:01

Fredrik Hedblad


2 Answers

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.

like image 176
marc_s Avatar answered Jan 22 '23 16:01

marc_s


select 
  A.*
from
  A
join
  B on A.B_GUID = B.GUID and A.Value <> B.Value
like image 36
heximal Avatar answered Jan 22 '23 18:01

heximal