[英]Return not all, but only first item of each joined table item
SELECT Id
FROM Container_A
JOIN Container_B
ON
Container_A.Container_B_FK = Container_B.Id
ORDER BY Container_A.Id
This query return all elements of all Container_A items related to Container_B. 该查询返回与Container_B相关的所有Container_A项的所有元素。 The question is - How to get only first (with min Id) item related to each Container_B item.
问题是-如何仅获取与每个Container_B项目相关的第一个(带有最小ID)项目。
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
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
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
The problem with queries like this is that "first" has no meaning at all unless you specify what the order of the items are within the group. 此类查询的问题在于,除非您指定项目在组中的顺序,否则“第一”根本没有任何意义。 If you want the lowest item id, then you can group on the container b and use the
min
aggreagate to get the lowest item id from each group: 如果您想要最低的项目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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.