Join MySQL自引用联接

Join MySQL自引用联接,join,self-reference,mysql5,Join,Self Reference,Mysql5,我有两张桌子: Customers ( int(11) Id, varchar(255) Name, int(11) Referred_ID -- Referred_ID being reference to an Id field -- (no key on that field) and ) 另一个表格是: Invoices ( int(11) Id, date Billing_date,

我有两张桌子:

Customers (
    int(11) Id, 
    varchar(255) Name, 
    int(11) Referred_ID -- Referred_ID being reference to an Id field 
                        -- (no key on that field) and 
)
另一个表格是:

Invoices (
    int(11) Id, 
    date Billing_date, 
    int(11) Customer_ID
)
我想选择发票的Id、开票日期以及最重要的客户名称

现在我只能通过这样的查询来选择他的推荐人的ID:

SELECT Invoices.Id, Invoices.Billing_date, Customers.Name, Referred_ID
    FROM Invoices 
    INNER JOIN Customers ON Invoices.Customer_Id = Customers.Id;
我应该如何修改查询以将引用的\u ID替换为其所有者名称


顺便说一下,这是一个类似于2015年的MySQL。

在join中使用Customers表两次

 SELECT Invoices.Id, Invoices.Billing_date,
 c1.Name as customername,
c1.Referred_ID,
c2.Name as refername 
FROM Invoices INNER JOIN Customers c1 ON Invoices.Customer_Id = c1.Id
join Customers c2 on  c1.Id=c2.Referred_ID 

您可以使用两次使用别名的客户加入所提及的客户

    SELECT Invoices.Id, Invoices.Billing_date, Customers.Name, Referred.Name 
    FROM Invoices 
    INNER JOIN Customers ON Invoices.Customer_Id = Customers.Id
    INNER JOIN Customers Referred on Referred.id =  Customers.Referred_ID;

我没有测试它,但我想下面应该适用于您的案例选择Invoices.Id,Invoices.Billing\u date,MainCustomer.Name,RefCustomer.Name FROM Invoices INNER JOIN Customers AS maincuster ON Invoices.Customer_Id=maincuster.Id LEFT JOIN Customers AS RefCustomer ON RefCustomer.Id=maincuster.refered_Id是类似2015的MySQL…-这是MySQL 5.xIn MySQL 5.x,您可以遍历有限数量的引用。如果你想直接转诊,那很容易。如果您需要将初始引用返回到第一个引用,则需要MySQL 8.x递归CTE。@tnsaturday立即检查plz有一个typo@tnsaturday我错过了比赛