Yes, the created_by column values should be the user_id, for at least these three reasons -
- It will use the least amount of storage space.
- It will result in the fastest queries.
- It will allow the email address to be edited, without requiring you to update all the data related to a user.
In the first post in this thread, in the second query, do you understand what the SELECT COUNT(expr)
and the GROUP BY column(s)
terms do? GROUP BY ⌠consolidates rows having the same column(s) values together. COUNT(expr) counts the number of non-null values for expr in each group. If you use COUNT() without a GROUP BY, you get the count value for all the rows that the query matched.
So, starting with the first query, where you are selecting some user columns FROM the users table, just add the things you are selecting from the JOINed query, add the JOIN table and the ON ⌠condition, and add the GROUP BY term so that the COUNT() term will have something per group to count.
Note: If you use table alias names, such as u and d for this example query, then always use alias.column
syntax, even in the cases where they are not required, it will be clearer to you, and anyone reading your query, what you are trying to accomplish.
Note: almost every SELECT query should have an ORDER BY term to get the data in the order that you want it. When you use a GROUP BY, this causes an âinternalâ ORDER BY the columns in the GROUP BY. If you want the data in a different order than produced by that, you need to add an ORDER BY term.
The first query after adding the things you are selecting from the JOINed query and adding table alias names -
SELECT
u.user_id, u.name, u.email, COUNT(d.device_id) AS count
FROM users u
Note: selecting created_by at this point is redundant since it will be the same as the user_id (email in your current design.)
The above query after adding the JOIN table and ON ⌠condition -
SELECT
u.user_id, u.name, u.email, COUNT(d.device_id) AS count
FROM users u
INNER JOIN devices d ON u.user_id = d.created_by
The above query after adding the GROUP BY term, so that the COUNT() term will have something to count per group -
SELECT
u.user_id, u.name, u.email, COUNT(d.device_id) AS count
FROM users u
INNER JOIN devices d ON u.user_id = d.created_by
GROUP BY u.user_id
Note: you should group by something in the âparentâ table in a query, since there may not be any âchildâ values for all types of join queries.