I have two tables, Table1 and Table2. I want to select distinct rows in Table2 that are not contained in Table1. Here is an example:
Table1
| A | | sem|
------------------
1. | aa | | 1 |
---------------
2. | bb | | 1 |
----------------
3. | aa | | 2 |
-----------------
4. | cc | | 2 |
---------------
Table2
| B |
------
1. | aa |
------
2. | aa |
------
3. | bb |
------
4. | cc |
------
5. | cc |
------
6. | ee |
------
7. | ee |
------
I would want the those row who is not common in this two table when sem = 1 like output for sem = 1 result
1 Answer. Here, LEFT JOIN is used to return all the rows from TableA even though they don't match with the rows in TableB. You can observe that WHERE tb.ID IS NULL clause; there will be no records in TableB for the particular ID from TableA.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
To get all of the rows from just one of the tables – the matched rows as well as the unmatched rows – you need to use the LEFT JOIN or the RIGHT JOIN .
You could try something like this.
SELECT B
FROM Table2 b
WHERE NOT EXISTS (
SELECT *
FROM Table1 a
WHERE a.A = b.B)
From what I can gather, the reason why yours isn't working is because your getting all the values that ARE in both table1 and table2. What you should be doing is like what I did above. Get all the values that are in both tables and check which values in both tables are NOT within the result set, that is why i have set up a sub-query. I'm a little rusty on my SQL so take what i've said with a gain of salt.
You can do this with an outer join
and a where
clause. In this case, a right outer join, I think:
SELECT cd.cGenotype
FROM dbo.TestResults tr right outer join
dbo.CombinedData cd
ON (tr.TestResult = cd.cGenotype)
where tr.testresult is null
GROUP BY cd.cGenotype
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With