MySQL – Using LIMIT on Table with One-to-Many Relationship

join;MySQL

I have 3 tables (A, B and C) that connect 1:m:1. I need to JOIN the 3 tables and apply a limit not on the total number of records, but on the number of records used from table A. This means that more records in total than the limit will be returned.

Here is a fiddle. This uses MySQL of:

SELECT A.id as Aid, A.name, C.id AS Cid, C.item
FROM A
INNER JOIN B b ON A.id = B.Aid
INNER JOIN C c ON B.Cid = C.id
WHERE A.owner = 1
ORDER BY A.id DESC
LIMIT 3

I would like to limit the number of records used from table A to 3, even though that means that 4 records will result (the ones connected to Aid's of 4, 3 and 2) because there are multiple records in table C that relate to those 3 records in table A.

I am wondering if perhaps this needs to use a SELECT (that has a LIMIT of 3) inside another SELECT that joins to tables B and C, but I don't know how to do this.

Best Answer

Like:

SELECT Al.id AS Aid,
       Al.name,
       C.id AS Cid,
       C.item
FROM
  (SELECT A.id,
          A.name
   FROM A
   WHERE A.owner = 1
   ORDER BY A.id DESC
   LIMIT 3) AS Al
INNER JOIN B b ON Al.id = B.Aid
INNER JOIN C c ON B.Cid = C.id

fiddle