TransWikia.com

how to get collection based on number of duplicate foreign keys?

Database Administrators Asked on November 8, 2021

I have a batch table, and an item table, the relationship is the batch has many items (item has a batch_id foreign key).

How would I make a query that will find the batches which have more than 100 items?

One Answer

SELECT b.* FROM
    batch b LEFT JOIN
    item i ON i.batch_id = b.batch_id
GROUP BY b.batch_id HAVING COUNT (i.batch_id) > 100

To get the count by batch_id

SELECT b.batch_id, COUNT(i.batch_id)
FROM
    batch b LEFT JOIN
    item i ON i.batch_id = b.batch_id
GROUP BY b.batch_id HAVING COUNT (i.batch_id) > 100

Answered by Thirumal on November 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP