简体   繁体   中英

Perform an INNER JOIN with more than 2 tables in MySQL

I just recently learned about SQL INNER JOIN and I thought of applying it on a project so basically I have three tables

  • payers
  • discounts
  • items

Now I was just wondering if I can return the results from both of the three tables at once using an INNER JOIN with both of the 3 tables or is it only possible with 2 tables?

If it is possible to use an INNER JOIN with more than 2 tables then kindly please guide me on how to do it and if not then tell me how to do it in any other ways possible.

Now this is the query that I currently have which doesn't work as expected:

SELECT *
FROM payers
INNER JOIN discounts AND items
ON payers.id = discounts.id AND ON payers.id = items.id;

You want two joins. The syntax is:

SELECT *
FROM payers p
INNER JOIN discounts d ON d.id = p.id
INNER JOIN items     i ON i.id = p.id

Side notes:

  • you did not show your actual schema, so this uses the join conditions described in your attempt; you might need to review that

  • table aliases make the query shorter to write and easier to read

  • SELECT * is generally not good practice; instead, I would recommend enumerating the columns you want in the SELECT clause, and properly aliasing conflicting columns names, if any (here, all three tables have a column called id , which would cause ambiguity in the resultset)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM