简体   繁体   English

从一对多关系中仅检索一条记录

[英]Retrieve only one record from ONE-TO-MANY relationship

I have 2 tables. 我有2张桌子。 One is Agent and the other one is Agent_Contact . 一个是Agent ,另一个是Agent_Contact The Agent_Contact table is there to maintain the contact information of Agent . Agent_Contact表用于维护Agent的联系信息。

The relationship from Agent to Agent_Contact is One-To-Many which means an Agent can have many Agent_Contacts AgentAgent_Contact联系的关系是One-To-Many ,这意味着Agent可以有多个Agent_Contacts

The Agent_Contact is holding the Foreign Key of Agent . Agent_Contact持有AgentForeign Key

There can be Agents that who do not have any Agent_Contact as well. 可以有Agents没有任何谁Agent_Contact为好。

Now, please have a look at the below code. 现在,请看下面的代码。

SELECT Agent.*,
Agent_Contact.*
FROM Agent
LEFT JOIN Agent_Contact ON Agent.idAgent = Agent_Contact.idAgent

Now, this returns all the Agents with their Agent_Contact s( If they have any). 现在,这将返回所有具有其Agent_Contact (如果有)的Agents However imagine one Agent got 15 Agent_Contact s, then it will return 15 rows. 但是,假设一个Agent得到了15个Agent_Contact ,那么它将返回15行。

This is not what I want. 这不是我想要的。 Once Agent_Contact per one Agent is enough. 每个Agent一个Agent_Contact就足够了。 But how can I modify the above sql query to achieve this task? 但是,如何修改上面的sql查询来完成此任务?

Since there is no rule to which contact must be returned, it is enough to add a group by clause. 由于没有任何必须返回联系的规则,因此添加一个group by子句就足够了。

SELECT Agent.*,
Agent_Contact.*
FROM Agent
LEFT JOIN Agent_Contact ON Agent.idAgent = Agent_Contact.idAgent
GROUP Agent.idAgent

If you only want 1 agent_contact returned per agent returned then the question is "which agent_contact do you want returned?" 如果您只希望每个返回的agent返回1个agent_contact则问题是“您要返回哪个agent_contact?”。

That's like selecting a classroom full of 20 students and saying "Please return 1 student." 这就像选择一个可容纳20名学生的教室,然后说“请返回一名学生”。 Well...which student do you want? 好吧...你想要哪个学生?

When it comes to selecting your Agent_Contact, you could select then alphabetically, or the one with the longest name, or something that will reduce the number of agent_contacts down to 1. 当谈到选择你的Agent_Contact,您可以选择按字母顺序,然后,或具有最长的名字,或东西,这将降低agent_contacts的数量减少到1。

This query selects the agent_contact with the maximum name. 此查询选择具有最大名称的agent_contact。 You can use whatever agent_contact column you want, it just has to be put in an aggregate function that will return only one kind. 您可以使用任何所需的agent_contact列,只需将其放在仅返回一种类型的聚合函数中即可。

SELECT t.Id, ac.* FROM
(SELECT Agent.Id, Max(AgentContact.Name)
FROM Agent
LEFT JOIN Agent_Contact ON Agent.idAgent = Agent_Contact.idAgent
GROUP BY Agent.Id) as t
INNER JOIN Agent_Contact as ac ON t.Name = ac.Name

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

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