This is the data structure:
stores { id, name, city_id, owner_id }
cities { id, name }
store_managers { user_id, store_id }
products { id, name, store_id }
users { id, name }
_______________________________________
#note: many users can manage the same store, and the same user can manage
many stores.
I need to get, in one query:
- The stores that owned by the user that its id I will provide. [from stores, when owner_id = some_number]
- For each store, the city that is attached too. [from cities]
- The users that have manage privileges to the store. [from store_managers]
- the COUNT of products that is assigned to each store.
I need it to be in one query.
The DB is MYSQL
fixed, added the missing foreign key
my mistake, thanks
Assuming that each store is only attached to one city and you forgot the foreign key, it might look something like this (MySQL specific as I learned before):
However, you already see that it’s not good fetching all things together, as you can only retrieve the names within one string or you will get several rows containing the same store_id. Unless you really want the names in a concatenated list, you have to explode the again which will lead to problems as soon as a name contains a comma. If you do not group, you have to iterate over all rows with PHP later and manipulate them. Sometimes it’s better to make two queries, but that depends on how you need the names of the users.
Often when putting to much stuff into one single query you will suffer from problems later. In this case everything is still manageable, but as soon as you want mulitple counts at once it can get dangerous.
Can still contain some mistakes, just written directly without testing.