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. The question is - How to get only first (with min Id) item related to each Container_B item.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.