Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this sql statement

Tags:

sql

tsql

I have 2 tables:
T1(IDa,IDb) : has data like this

    IDa IDb  
    1   2  
    3   4  
    5   6  
    7   8

and T2(IDc,IDd) : with data like this

    IDc IDd  
    1   2  
    4   5  
    3   6  
    7   8  

and the Identity for each table is the pair of IDs:

  • T1, Identity is IDa and IDb
  • T2 is IDc and IDd

The question is: How to retrieve the "Not matched" records from the two tables??? In this case,

  • the matched are 1,2 and 7,8
  • the "not matched" are: 3,4 $ 5,6 $ 4,5 $ 3,6

I can do that using strings and concatenation. Did anyone have a method using inner join or any other method??

like image 842
RMohammed Avatar asked Jul 01 '10 08:07

RMohammed


People also ask

What is this * in SQL?

/* means a start of a multiline comment. For example: /* CREATE PROC A_SAMPLE_PROC BEGIN AS SELECT * FROM A_SAMPLE_TABLE END */ while -- means single line comment. Keyboard shortcut for commenting in MS SQL Server Studio is Ctrl + K, Ctrl + C.

What is %s means in SQL?

%s is a placeholder used in functions like sprintf. Check the manual for other possible placeholders. $sql = sprintf($sql, "Test"); This would replace %s with the string "Test". It's also used to make sure that the parameter passed actually fits the placeholder.

What is SQL statement example?

An SQL SELECT statement retrieves records from a database table according to clauses (for example, FROM and WHERE ) that specify criteria. The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value';

Why is (+) used in SQL?

The plus sign is Oracle syntax for an outer join. There isn't a minus operator for joins. An outer join means return all rows from one table. Also return the rows from the outer joined where there's a match on the join key.


1 Answers

DECLARE @Result nvarchar(max)


SELECT @Result = ISNULL(@Result + '$','') + 
       CAST(ISNULL(IDa,IDc) AS VARCHAR(5)) + ',' +  
            CAST(ISNULL(IDb,IDd) AS VARCHAR(5))
FROM T1 FULL OUTER JOIN T2
ON T1.IDa = T2.IDc AND  T1.IDb = T2.IDd
WHERE T1.IDa IS NULL OR T2.IDc IS NULL

Edit Of course if the $ and , is not required just use

SELECT  ISNULL(IDa,IDc), ISNULL(IDb,IDd)
FROM T1 FULL OUTER JOIN T2
ON T1.IDa = T2.IDc AND  T1.IDb = T2.IDd
WHERE T1.IDa IS NULL OR T2.IDc IS NULL

Or another way, just for kicks (MS SQL Server 2005+)

SELECT IDa, IDb from T1
EXCEPT
SELECT IDc, IDd from T2
UNION ALL
(
SELECT IDc, IDd from T2
EXCEPT
SELECT IDa, IDb from T1
)
like image 146
Martin Smith Avatar answered Sep 28 '22 08:09

Martin Smith