简体   繁体   English

在 MySQL 中对超过 2 个表执行 INNER JOIN

[英]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我最近才了解到 SQL INNER JOIN ,我想将它应用到一个项目上,所以基本上我有三个表

  • 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?现在我只是想知道我是否可以同时使用三个表的INNER JOIN一次返回三个表的结果,还是只能使用 2 个表?

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.如果可以使用超过 2 个表的INNER JOIN ,请指导我如何操作,如果没有,请告诉我如何以任何其他可能的方式进行操作。

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; SELECT *通常不是好的做法; 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)相反,我建议在SELECT子句中枚举您想要的列,并适当地为冲突的列名(如果有)进行别名(这里,所有三个表都有一个名为id的列,这会导致结果集中的歧义)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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