[英]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
Agent
与Agent_Contact
联系的关系是One-To-Many
,这意味着Agent
可以有多个Agent_Contacts
The Agent_Contact
is holding the Foreign Key
of Agent
. Agent_Contact
持有Agent
的Foreign 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.