TIL

Restricting results in GROUP_CONCAT with FIND_IN_SET

GROUP BY is used to group rows with similar values in a column, while GROUP_CONCAT is used to concatenate the values of a column. FIND_IN_SET is a function that searches for a value within a comma-separated list.

When used together, GROUP BY and GROUP_CONCAT can be used to concatenate values within a group, and HAVING FIND_IN_SET can be used to filter groups based on the presence or absence of a specific value within the concatenated string.

SELECT
    p.id,
    group_concat(
        c.kind
        ORDER BY
            c.KIND
    ) AS kinds
FROM
    photo AS p
    LEFT JOIN photocategory AS c ON p.id = c.photo_id
WHERE
    p.status = "approved"
GROUP BY p.id HAVING NOT FIND_IN_SET(0, kinds)
LIMIT 3;
+--------+-------+
| id     | kinds |
+--------+-------+
| 4112   | 1     |
| 5968   | 2     |
| 5824   | 1,2   |
+--------+-------+