Mysql连接同一个表中其他字段中使用的多个ID(Self Join)

时间:2013-09-16 13:21:17

标签: mysql self-join

我确实尝试遵循此answer

但在我的情况下,我使用pk id来由同一个表的其他字段使用

样本表:

1。客户

字段:

  

Customer_ID,名称,Category_ID, Realty_Firm

2.Category

字段:

  

Category_ID,描述

类别的示例数据:

Category_ID | Description
1           | Agent
2           | Broker

客户样本数据:

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

注1: Realty_Firm字段数据来自Broker客户ID(6和7是Category Broker的ID)

注2:只有在选择的类别是代理(1)时才需要Realty_Firm字段

问题:如何进行按类别对客户进行分组的查询? 看起来像一个简单的工作,但问题是如何将Realty_Firm字段加入同一个表的Customer_ID?

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

上面的查询使用不同的别名对Customer表进行了双重连接,但只返回了Realty_Field值(Broker)的行,而不是代理的所有记录都属于Brokers。

示例查询输出 (显示可重新记录的记录而不是ID,以便于参考和为了示例):

Description | Broker       | Agent
Broker      | BrokerName1  | AgentName1
Broker      | BrokerName1  | AgentName2
Broker      | BrokerName1  | AgentName3
Broker      | BrokerName1  | AgentName4
Broker      | BrokerName1  | AgentName5

2 个答案:

答案 0 :(得分:1)

尝试使用LEFT JOIN代替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

答案 1 :(得分:1)

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;

输出

AgentName1 |    BrokerName1 | Broker
AgentName2 |    BrokerName1 | Broker
AgentName3 |    BrokerName1 | Broker
AgentName4 |    BrokerName1 | Broker
AgentName5 |    BrokerName2 | Broker