http://sqlfiddle.com/#!9/f9a33f/5/0http://sqlfiddle.com/#!9/0bcc34/3/0
SELECT d.`id`, COUNT(da.`doc_id`)
FROM `docs` d
LEFT JOIN `docs_scod_a` da ON da.`doc_id` = d.`id`
LEFT JOIN `scod_a` a ON a.id = da.`doc_id``scod_a_id`
WHERE a.`ver_a` IN ('AA', 'AC''AB')
GROUP BY d.`id`;
| id | COUNT(da.`doc_id`) |
|----|--------------------|
| 1 | 32 |
| 2 | 1 |
| 3 | 2 |
http://sqlfiddle.com/#!9/fee4c6/33/0http://sqlfiddle.com/#!9/d89a4e/1/0
SELECT d.`id`, COUNT(db.`doc_id`)
FROM `docs` d
LEFT JOIN `docs_scod_b` db ON db.`doc_id` = d.`id`
LEFT JOIN `scod_b` b ON b.id = db.`doc_id``scod_b_id`
WHERE b.`ver_b` IN ('BA', 'BB')
GROUP BY d.`id`;
| id | COUNT(db.`doc_id`) |
|----|--------------------|
| 1 | 32 |
| 2 | 1 |
| 3 | 2 |
http://sqlfiddle.com/#!9/fee4c6/36/0http://sqlfiddle.com/#!9/1d2954/2/0
SELECT d.`id`, COUNT(da.`doc_id`), COUNT(db.`doc_id`)
FROM `docs` d
LEFT JOIN `docs_scod_a` da ON da.`doc_id` = d.`id`
LEFT JOIN `scod_a` a ON a.id = da.`doc_id``scod_a_id`
LEFT JOIN `docs_scod_b` db ON db.`doc_id` = d.`id`
LEFT JOIN `scod_b` b ON b.`id` = db.`doc_id``scod_b_id`
WHERE a.ver_a IN ('AA''AC', 'AC''AB') AND b.ver_b IN ('BA', 'BB')
GROUP BY d.`id`;
| id | COUNT(da.`doc_id`) | COUNT(db.`doc_id`) |
|----|--------------------|--------------------|
| 1 | 32 | 32 |
| 2 | 01 | 1 |
| 3 | 2 | 02 |
| id | COUNT(da.`doc_id`) | COUNT(db.`doc_id`) |
|----|--------------------|--------------------|
| 21 | 34 | 4 |
| 3 | 2 | 2 |
| id | SUM(COUNT(da.`doc_id`) + COUNT(db.`doc_id`))|
|----|---------------------------------------------|
| 1 | 64 |
| 2 | 12 |
| 3 | 24 |