Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AND in an INNER JOIN

Tags:

sql

inner-join

I am fairly new with SQL would like to understand the logic below.

SELECT *
FROM Table A A1 
INNER JOIN TABLE B B1 ON B1.ID = A1.ID AND A1 = 'TASK';

Not sure if this is a clear detail but please let me know. Thanks!

like image 661
sonnymoon Avatar asked Aug 31 '17 17:08

sonnymoon


People also ask

Can I use and in inner join?

With the AND in the inner join you can specify it even more. Join the tables on the columns, where A1. Column = 'TASK' and throw away the rest. You could just as easily move the AND to the WHERE -Clause.

What is inner join with example?

Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same for both the students and courses tables.

Can we use group by and join together?

GROUP BY With JOIN Example In above example, Employee and Department are joined using the common column DeptID. In the above example, JOIN and GROUP BY both clauses used together in a single query. After joining both tables(Employee and Department), joined table grouped by Department name.


2 Answers

SELECT *
FROM Table A A1
    INNER JOIN TABLE B B1 ON B1.ID = A1.ID AND A1.Column = 'TASK'

is the same as

SELECT *
FROM Table A A1
    INNER JOIN TABLE B B1 ON B1.ID = A1.ID
WHERE A1.Column = 'TASK'

It's even the same performance wise, it's just a different way to write the query. In very large queries it can be more readable to use an AND directly on an INNER JOIN instead of "hiding" it the in the WHERE part.

like image 60
waka Avatar answered Oct 03 '22 20:10

waka


This wouldn't run at all

SELECT *
FROM Table A A1 INNER JOIN
     TABLE B B1 
     ON B1.ID = A1.ID AND A1 = 'TASK';

This will run because I added a column name (SomeColumn):

SELECT *
FROM Table A A1 INNER JOIN
     TABLE B B1 
     ON B1.ID = A1.ID AND A1.SomeColumn = 'TASK';

And is the same as this

SELECT *
FROM Table A A1 INNER JOIN
     TABLE B B1 
     ON B1.ID = A1.ID 
WHERE A1.SomeCoumn = 'TASK';

Whenever you join to a constant it is pretty much the same as adding an additional criterion to the where clause. The only reason to put it up with the join is for code clarity.

like image 42
John Wu Avatar answered Oct 03 '22 19:10

John Wu