SELECT Id
FROM Container_A
JOIN Container_B
ON
Container_A.Container_B_FK = Container_B.Id
ORDER BY Container_A.Id
此查询返回与Container_B相关的所有Container_A项的所有元素。 问题是 - 如何只获得与每个Container_B项目相关的第一个(带有min Id)项目。
答案 0 :(得分:1)
SELECT top 1 *,min(Id) as minimum
FROM Container_A
JOIN Container_B
ON
Container_A.Container_B_FK = Container_B.Id
group by Container_A.id,Container_B.id
ORDER BY minimum
答案 1 :(得分:1)
SELECT
MIN(a.Id) AS a_id,
b.Id AS b_id
FROM Container_A a
JOIN Container_B b
ON (Container_A.Container_B_FK = Container_B.Id)
GROUP BY b.Id
ORDER BY a_Id
答案 2 :(得分:1)
SELECT Id
FROM Container_A
JOIN Container_B
ON Container_A.Container_B_FK = Container_B.Id
ORDER BY Container_A.Id ASC
LIMIT 0,1
答案 3 :(得分:1)
这样的查询存在的问题是,“first”根本没有任何意义,除非您指定项目的顺序在组内。如果您想要最低的商品ID,那么您可以对容器b进行分组并使用min
aggreagate从每个组中获取最低的商品ID:
select
b.Id,
min(a.Id) as A_Id
from
Container_B b
inner join Container_A a on a.Container_B_FK = b.Id
group by
b.Id
order by
b.Id