Home > Database > Mysql Tutorial > How Do I Correctly Join Three Tables in SQL Using a Common Foreign Key?

How Do I Correctly Join Three Tables in SQL Using a Common Foreign Key?

DDD
Release: 2024-12-21 15:48:11
Original
601 people have browsed it

How Do I Correctly Join Three Tables in SQL Using a Common Foreign Key?

Multi-Table Joins in SQL

Joining multiple tables in SQL allows you to combine data from different sources based on specific criteria. In your case, you want to join three tables, each with a foreign key column named table1Id.

Incorrect Syntax

Your attempted query contains incorrect syntax. Instead of repeating the equality condition multiple times using =table1Id=table1Id, you should use parentheses to group the joins:

$result = mysql_query("SELECT * 
FROM table1 
INNER JOIN table2
      ON table1.primaryKey = table2.table1Id
INNER JOIN table3
      ON table1.primaryKey = table3.table1Id");
Copy after login

Corrected Syntax

The corrected query joins tables table1, table2, and table3 on the common column primaryKey. This query will return rows where the primaryKey values in all three tables match.

Here's a breakdown of the corrected query:

  • SELECT * FROM table1: Selects all columns from table1.
  • INNER JOIN table2 ON table1.primaryKey = table2.table1Id: Joins table1 and table2 on the common column primaryKey.
  • INNER JOIN table3 ON table1.primaryKey = table3.table1Id: Further joins table2 and table3 on the same common column from table1.

By using proper syntax and grouping the joins with parentheses, you can successfully join multiple tables on the equality of a foreign key.

The above is the detailed content of How Do I Correctly Join Three Tables in SQL Using a Common Foreign Key?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template