Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL join and exclude?

Tags:

join

php

mysql

I have two tables, table A one with two columns: IP and ID, and table B with columns: ID and extra information. I want to extract the rows in table B for IPs that are not in table A. So if I have a rows in table A with

id = 1
ip = 000.000.00
id = 2
ip = 111.111.11

and I have rows in table B

id = 1
id = 2

then, given ip = 111.111.11, how can I return row 1 in table B?

like image 710
Rio Avatar asked Mar 13 '11 03:03

Rio


People also ask

Can we use != IN join?

Such joins are called non-equi JOINs, and they are also possible in SQL. When you join two tables using other conditional operators, beyond the equal sign, non-equi JOINs come into play. Comparison operators, like <, >, <=, >=, != , and <> and the BETWEEN operator work perfectly for joining tables in SQL.

How do I exclude something in MySQL?

To check records which are NULL, use IS NULL. However, to exclude any of the records, use the NOT IN clause. Use both of them in the same query.

What is exclusion join?

Exclusion join is a product, merge, or hash join where only the rows that do not satisfy (are NOT IN) any condition specified in the request are joined. In other words, exclusion join finds rows in the first table that do not have a matching row in the second table. Exclusion join is an implicit form of the outer join.

Which is better join or where clause?

“Is there a performance difference between putting the JOIN conditions in the ON clause or the WHERE clause in MySQL?” No, there's no difference. The following queries are algebraically equivalent inside MySQL and will have the same execution plan.


2 Answers

The simplest and most easy-to-read way to spell what you're describing is:

SELECT * FROM `B` WHERE `ID` NOT IN (SELECT `ID` FROM `A`)

You should be aware, though, that using a subquery for something like this has historically been slower than doing the same thing with a self-join, because it is easier to optimise the latter, which might look like this:

SELECT
   `B`.*
FROM
   `B`
LEFT JOIN
   `A` ON `A`.`ID` = `B`.`ID`
WHERE
   `A`.`ID` IS NULL

However, technology is improving all the time, and the extent to which this is true (or even whether this is true) depends on the database software you're using.

You should test both approaches then settle on the best balance of readability and performance for your use case.

like image 149
Lightness Races in Orbit Avatar answered Sep 29 '22 10:09

Lightness Races in Orbit


select b.id, b.* 
from b
left join a on a.id = b.id
where a.id is null

This'll pull all the rows in B that have no matching rows in A. You can add a specific IP into the where clause if you want to try for just that one ip.

like image 37
Marc B Avatar answered Sep 29 '22 10:09

Marc B