I have four tables: foods, recipes, users, and activities.
The activities table has schema:
mysql> describe activities;
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | YES | MUL | NULL | |
| recipe_id | int(11) | YES | MUL | NULL | |
| name | varchar(255) | YES | | NULL | |
| amount | int(11) | YES | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
The recipes table has schema:
mysql> describe recipes;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| image_url | varchar(255) | YES | | NULL | |
| user_id | int(11) | YES | MUL | NULL | |
| food_id | int(11) | YES | MUL | NULL | |
+--------------+--------------+------+-----+---------+----------------+
The foods-recipes has a one-to-many relationship, and recipes-activities has a many-to-many relationships.
Now I want to select all user activities on foods. I consider a user acting on a food if he acts on a recipe of that food. If a user acts on multiple recipes of the same food, only one should be counted.
Could anyone tell me how to write the query?