Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows with no match between two tables by sem

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

| B |

  1. | cc |
  2. | ee |
like image 470
leschandrew Avatar asked Jan 28 '13 02:01

leschandrew


People also ask

How do you SELECT rows with no matching entry in the same table?

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.

How would you return data from 2 tables even if there are no matches?

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.

How can I get matched and unmatched records from two tables in SQL?

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 .


2 Answers

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.

like image 153
user798774 Avatar answered Sep 23 '22 13:09

user798774


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
like image 25
Gordon Linoff Avatar answered Sep 23 '22 13:09

Gordon Linoff