Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a left join and checking if the row existed along with another check in where clause

Tags:

I have the following tables:

Users Banned  SELECT u.* FROM Users WHERE u.isActive = 1     AND       u.status <> 'disabled' 

I don't want to include any rows where the user may also be in the Banned table.

What's the best way to do this?

I could do this put a subquery in the where clause so it does something like:

u.status <> 'disabled' and not exist (SELECT 1 FORM Banned where userId = @userId) 

I think the best way would be to do a LEFT JOIN, how could I do that?

like image 218
loyalflow Avatar asked Oct 29 '12 19:10

loyalflow


People also ask

Can you use a WHERE clause in a join?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.

What is the difference between left join with WHERE clause and left join with WHERE clause?

When you use a Left Outer join without an On or Where clause, there is no difference between the On and Where clause. Both produce the same result as in the following. First we see the result of the left join using neither an On nor a Where clause.

Can we use WHERE clause in left outer join?

An outer join returns all of the rows that the equivalent inner join would return, plus non-matching rows from one or both tables. In the FROM clause, you can specify left, right, and full outer joins. In the WHERE clause, you can specify left and right outer joins only.

WHERE exists vs LEFT join?

EXISTS and NOT EXISTS both short circuit - as soon as a record matches the criteria it's either included or filtered out and the optimizer moves on to the next record. LEFT JOIN will join ALL RECORDS regardless of whether they match or not, then filter out all non-matching records.


1 Answers

According to this answer, in SQL-Server using NOT EXISTS is more efficient than LEFT JOIN/IS NULL

SELECT  * FROM    Users u WHERE   u.IsActive = 1 AND     u.Status <> 'disabled' AND     NOT EXISTS (SELECT 1 FROM Banned b WHERE b.UserID = u.UserID) 

EDIT

For the sake of completeness this is how I would do it with a LEFT JOIN:

SELECT  * FROM    Users u         LEFT JOIN Banned b             ON b.UserID = u.UserID WHERE   u.IsActive = 1 AND     u.Status <> 'disabled' AND     b.UserID IS NULL        -- EXCLUDE ROWS WITH A MATCH IN `BANNED` 
like image 192
GarethD Avatar answered Oct 21 '22 13:10

GarethD