首页 > 解决方案 > Can you use an AND statement in a JOIN in SQL

问题描述

Suppose you have two tables A and B and you are trying to write a JOIN query, is the following possible:

SELECT A.col1, B.col1 
FROM A JOIN B on (A.col2 = B.col2 AND B.col3 = 'hello')

Will this return a table of col1 from table A and col2 from table B where there is a match in the second column across the tables and the third column of table B is 'hello'?

I.e. it will only return rows that are matching in col2 and this is further reduced to the cases where col3 in table B is 'hello'?

标签: sql

解决方案


Yes. You can use:

  1. Below will Join the Records in B table (Col3='hello') with A:
SELECT A.col1, B.col1 
FROM A JOIN B on (A.col2 = B.col2 AND B.col3 = 'hello')
  1. Below will Join all Records in B table with A, And performing where at Result of A and B:
SELECT A.col1, B.col1 
FROM A JOIN B on A.col2 = B.col2
WHERE B.col3 = 'hello'

Both will give the same result when no other tables joined.


推荐阅读