Left JOIN syntax usage and instance
MySQL left JOIN syntax
The SQL (MySQL) left JOIN gets all the records in the left-hand table (table1), even if the right table (table2) does not have a corresponding matching record. The basic syntax for the left JOIN is as follows:
... From table1 left JOIN table2 on condition ...
MySQL Left JOIN Usage Example
Here are two raw data tables:
Article Article table:
User table:
We list all the articles and the corresponding users, even if no user's articles are listed.
SELECT ... Left JOIN ... The ON statement is as follows:
SELECT Article.aid,article.title,user.username from article left JOIN user on article.uid = User.uid
Return query results as follows:
As you can see, the obvious difference from the INNER JOIN is that the left table records are all taken out, even if the right table has no corresponding matching record.
Tips
The so-called records are "all" taken out, which is relative to the restriction of INNER JOIN. In fact, you can add a where condition or LIMIT to the following SQL statement to make a range limit on the result set like a generic SQL statement.
Is NULL
In the example above, all columns are set to NULL for the right table without a matching data record, so you can attach the IS null condition if you want to query this part of the record (such as a aid=4 article record in the example above, which is reflected in the lookup.):
SELECT Article.aid,article.title,user.username from article left JOIN user in
article.uid = User.uid WHERE User.uid is Null
Right JOIN syntax usage and instance
MySQL Right JOIN syntax
The SQL (MySQL) Right JOIN obtains all records of the right-hand table (table2), even if the left table (table2) does not have a corresponding matching record. The basic syntax for right JOIN is as follows:
... From table1 right JOIN table2 on condition ...
MySQL Right JOIN usages instance
Here are two raw data tables:
Article Article table:
User table:
We list all the users and the articles that they might have.
SELECT ... Right JOIN ... The ON statement is as follows:
SELECT Article.aid,article.title,user.username from article right JOIN user on article.uid = User.uid
Return query results as follows:
When you compare the results of a query returned by a LEFT join, the result of the right join returns exactly the opposite.
Is NULL
In the above example, all columns are set to NULL for a data record in the left table that does not match, so it is possible to attach the IS null condition to query this part of the record (for example, in the example above, for all users who do not have a corresponding article, such as the lookup Username=jack):
SELECT Article.aid,article.title,user.username from article left JOIN user on
article.uid = User.uid WHERE article.ai D is NULL