我想 return 通过一对多关系连接两个表的查询中的一行

I'd like to return a single row in a query that joins two tables through a one to many relationship

这是一个神谕系统。我有一个客户 table(一个)和一个帐户 table(多个)。坦率地说,我真的只想查询客户端 table,但由于设计不佳,客户端 table 需要一个数据元素,它只存在于帐户 table -该客户的所有帐户的值都相同,因此我真的只需要 return 一个帐户行,但我在完成此操作时遇到了问题。这是我试过的查询:

Select
c.client_num,
c.client_name,
a.agency_value
from client c
inner join account a on c.client_num = a.client_num
where a.account_num in (select a2.account_num from account a2 where rownum = 1)  

您需要明确指定如何从多条记录中挑选一条记录。这是一种方法 - 使用 MAX

Select
c.client_num,
c.client_name,
(SELECT 
 MAX(a.agency_value) agency_value 
 FROM account a 
 where c.client_num = a.client_num
 -- not sure if this line is required - if not please remove
 and a.account_num in (select a2.account_num from account a2 where rownum = 1)
 ) agency_value
from client c

请记住,通过实施这一点,您正在“巩固”您糟糕的 table 设计。

您绝对确定只有一个 agency_value 吗?使用查询查找拥有多个代理机构的任何客户:

 SELECT 
 a.client_num,
 COUNT(DISTINCT a.agency_value) CountOfAgencyValues,
 MAX(a.agency_value) max_agency_value,
 MIN(a.agency_value) max_agency_value 
 FROM account a 
 GROUP BY a.client_num
 HAVING COUNT(DISTINCT a.agency_value) > 1

根据您的意见和我自己的尝试,这里是最终满足我需求的代码:

select
c. client_num,
    (select a.agency_value
    from account a
    where a.client_num = c.client_num
    and rownum = 1)
from client c