Home > Database > Mysql Tutorial > How Do SQL Joins Combine Data from Multiple Tables?

How Do SQL Joins Combine Data from Multiple Tables?

Patricia Arquette
Release: 2025-01-05 02:47:41
Original
992 people have browsed it

How Do SQL Joins Combine Data from Multiple Tables?

How to Join Two Tables in SQL

In SQL, joining tables allows you to combine data from multiple tables based on a common column. You can use different types of joins, such as inner join, left join, right join, and full outer join.

Here's an example of using a left outer join to fetch data from two tables, A and B:

Tables:

TABLE A TABLE B
uid name uid address
1 test1 1 address1
2 test2 2 address2
3 test3 4 address3
4 test4

Query:

SELECT A.uid, A.name, B.address
FROM A
LEFT JOIN B ON A.uid=B.uid;
Copy after login

Output:

uid name address
1 test1 address1
2 test2 address2
3 test3 NULL
4 test4 address3

As you can see, the result includes all rows from table A and the matching rows from table B. For the row with uid=3 in table A, there is no matching row in table B, so the address column is set to NULL.

To understand how joins work, it's helpful to visualize the process. For a left outer join, the rows from the left table (A in this case) are considered first. For each row in the left table, the join condition is evaluated to find matching rows in the right table (B in this case). If a match is found, the data from both rows is combined into a single result row. If no match is found, the data from the left table alone is included in the result row, with any missing columns from the right table set to NULL.

Refer to the image at https://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_V2.png for a visual representation of joins.

The above is the detailed content of How Do SQL Joins Combine Data from Multiple Tables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template