Home > Database > Mysql Tutorial > Why Doesn't My SQL INNER JOIN With Multiple Tables Return Any Results?

Why Doesn't My SQL INNER JOIN With Multiple Tables Return Any Results?

Barbara Streisand
Release: 2024-12-17 00:04:23
Original
221 people have browsed it

Why Doesn't My SQL INNER JOIN With Multiple Tables Return Any Results?

Joining Multiple Tables Using SQL Inner JOIN

When working with relational databases, it is often necessary to combine data from multiple tables. SQL provides the INNER JOIN operator for this purpose.

To perform an inner join on two tables, you specify the equality condition between their primary and foreign keys. For example:

SELECT *
FROM table1
INNER JOIN table2
ON table1.primaryKey = table2.table1Id;
Copy after login

This query will return all rows from both tables that have matching primary and foreign keys.

To extend this to multiple tables, simply add additional INNER JOIN clauses to the query, using the same foreign/primary key equality condition. However, the following code is not returning any results:

SELECT *
FROM table1
INNER JOIN table2
INNER JOIN table3
ON table1.primaryKey = table2.table1Id = table3.table1Id;
Copy after login

The reason for this is that the equality condition must be specified separately for each table. The correct syntax is:

SELECT *
FROM table1
INNER JOIN table2
ON table1.primaryKey = table2.table1Id
INNER JOIN table3
ON table1.primaryKey = table3.table1Id;
Copy after login

This query will return all rows from table1 that have matching primary and foreign keys in table2 and table3.

The above is the detailed content of Why Doesn't My SQL INNER JOIN With Multiple Tables Return Any Results?. 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