For the depicted database scheme, it is necessary to create a query that will return a list of all accounts. For each account, select the fields account number, date of the account, customer name and customer name to which the current account customer refers. enter image description here

SELECT Invoices.id, Invoices.Billing_date, Customers.Name, Customers.Reffered_ID FROM second_test.Invoices, second_test.Customers WHERE Invoices.Customer_ID = Customers.id; 

Tell me how to display the name of the client that the client refers to (in this query, id is displayed instead of the name)?

  • Use join as an option - Nilsan

1 answer 1

It is necessary to join the Customers table through LEFT JOIN indicating the Referrer_ID link

 SELECT INV.id, INV.Billing_date, CUS.Name AS CUSTOMER_NAME, REF.Name AS REFERRER_NAME FROM second_test.Invoices INV INNER JOIN second_test.Customers CUS ON INV.Customer_ID = CUS.id LEFT JOIN second_test.Customers REF ON CUS.Referred_ID = REF.id 
  • Everything works, thank you. - Hektor Fektor