Sql 在一对多关系中选择一行
我有一对多的关系Sql 在一对多关系中选择一行,sql,oracle,Sql,Oracle,我有一对多的关系 Table 1: C_Id, Name Table 2: Id, Name 我只想从表2中为表C_Id中的每个Id选择一行 示例: Table 1 1 First Row 2 Second Row Table 2 1 First Row 1 1 First Row 2 2 Second Row 1
Table 1: C_Id, Name
Table 2: Id, Name
我只想从表2中为表C_Id中的每个Id选择一行
示例:
Table 1
1 First Row
2 Second Row
Table 2
1 First Row 1
1 First Row 2
2 Second Row 1
2 Second Row 2
我的查询结果是:
1 First Row 1 (First row for ID 1)
2 Second Row 1 (First row for ID 2)
我需要什么查询来获取此信息?从tab1、tab2中选择*,其中tab1.c_id=tab2.id和rownum=1;
SELECT t1.C_Id, MIN(t2.Name) -- or MAX, depending on your needs
FROM t1 INNER JOIN t2 ON (t1.C_Id = t2.Id)
GROUP BY t1.C_Id
--如果要对ace或desc进行排序,请使用order by。如果可以依赖表2的ID,那么这非常简单:
select t1.c_id
, t1.name
, t2.id as t2_id
from t1
join t2 on t1.name = t2.name
where t2.id = 1;
但是我怀疑你的实际情况更复杂。但可以使用ROW_NUMBER()解析函数轻松求解:
select c_id
, name
, t2_id
from (
select t1.c_id
, t1.name
, t2.id as t2_id
, row_number() over ( partition by t1.name
order by t2.id asc ) rn
from t1
join t2 on t1.name = t2.name
)
where rn = 1;
如何定义“ID 1的第一行”?您想要名称按字母顺序排在第一位的那一行吗?是否有您在此处未显示的其他列需要订购?