Mysql Joining multiple IDs used in other field within the same table (Self Join)

StackOverflow https://stackoverflow.com/questions/18829086

  •  28-06-2022
  •  | 
  •  

Question

I did try to follow this answer

But in my case, Im using the pk id to be used by the other field of the same table

Sample Tables:

1. Customer

Fields:

Customer_ID, Name, Category_ID, Realty_Firm

2.Category

Fields:

Category_ID, Description

Sample Data for Category:

Category_ID | Description
1           | Agent
2           | Broker

Sample Data for Customer:

Customer_ID  | Name    | Category_ID | Realty Firm
1            | AgentName1  | 1           | 6
2            | AgentName2  | 1           | 6
3            | AgentName3  | 1           | 6
4            | AgentName4  | 1           | 6
5            | AgentName5  | 1           | 7
6            | BrokerName1 | 2           | null
7            | BrokerName2 | 2           | null

Note 1: Realty_Firm field data comes from Broker Customer ID (6 and 7 are the IDs of Category Broker)

Note 2 : Realty_Firm field is only required if the Category selected is Agent(1)

Question: How will I make a query that will group Customer by Category? Seems like an easy work but the problem is How Can I join the Realty_Firm field to the Customer_ID of the same table?

Select Cat.Description, Custom.Name as Broker, Cust.Name as Agent From Customer as Cust 
Inner Join Category as Cat ON Cust.Category_ID=Cat.Category_ID 
INNER JOIN  Customer as Custom ON Custom.Customer_ID=Cust.Realty_Firm

The above query has double Join to the Customer table with different aliases but returns only the rows with Realty_Field value (Broker) and NOT the entire records of Agents belongs to Brokers.

Sample Query output (showing the redable record and not the ID for easy reference and for the sake of sample):

Description | Broker       | Agent
Broker      | BrokerName1  | AgentName1
Broker      | BrokerName1  | AgentName2
Broker      | BrokerName1  | AgentName3
Broker      | BrokerName1  | AgentName4
Broker      | BrokerName1  | AgentName5
Était-ce utile?

La solution

try with LEFT JOIN instead of INNER JOIN:

Select Cat.Description, Custom.Name as Broker, Cust.Name as Agent From Customer as Cust 
Inner Join Category as Cat ON Cust.Category_ID=Cat.Category_ID 
LEFT JOIN  Customer as Custom ON Custom.Customer_ID=Cust.Realty_Firm

Autres conseils

select a.name, b.name, c.description from customer a
left join customer b on a.realty_firm = b.customer_id
left join category c on b.category_id = c.category_iD
 where a.category_id = 1;

Outputs

AgentName1 |    BrokerName1 | Broker
AgentName2 |    BrokerName1 | Broker
AgentName3 |    BrokerName1 | Broker
AgentName4 |    BrokerName1 | Broker
AgentName5 |    BrokerName2 | Broker
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top