Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi column exist statement

I am trying to insert data to a table from another where data is not already exists

The table I am inserting the data into

CREATE TABLE #T(Name VARCHAR(10),Unit INT, Id INT)
INSERT INTO #T
    VALUES('AAA',10,100),('AAB',11,102),('AAC',12,130)

The table I am selecting the data from

CREATE TABLE #T1(Name VARCHAR(10),TypeId INT,Unit INT, Id INT)
INSERT INTO #T1
VALUES('AAA',3,10,100),('AAA',3,10,106)

In this case I want to select ('AAA',3,10,106) from #T1 because AAA,106 combination not exists in #T

Basically what I want is to populate unique Name and Id combination

I tried below which doesn't seems to work

SELECT *
FROM #T1
WHERE NOT EXISTS(SELECT * FROM #T)
like image 413
mrTester Avatar asked Mar 27 '17 11:03

mrTester


People also ask

How do you check if multiple columns exist in a table SQL?

The easiest and straightforward way to check for the column in a table is to use the information schema for column system view. Wright a select query for INFORMATION_SCHEMA. COLUMNS as shown below. If the query returns record, then the column is available in the table.

Can we use multiple columns in WHERE clause?

If you want compare two or more columns. you must write a compound WHERE clause using logical operators Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause.

Can we use exists in select statement?

The exists operator can be used with either of these statements- SELECT, UPDATE, INSERT or DELETE.

How do I select multiple columns based on condition in SQL?

When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.


1 Answers

You have to somehow correlate the two tables:

SELECT *
FROM #T1 
WHERE NOT EXISTS(SELECT * 
                 FROM #T
                 WHERE #T1.Name = #T.Name AND #T1.ID = #T.ID)

The above query essentially says: get me those records of table #T1 which do not have a related record in #T having the same Name and ID values.

like image 144
Giorgos Betsos Avatar answered Oct 25 '22 15:10

Giorgos Betsos