Ok, first off I think you are almost there. From looking at the schema and data one thing I have noticed is that you seem to have overlooked the fact that a friendship is bi-directional. So when you create a friend entry from a request you also need to create one in the other direction as well:
INSERT INTO `default_friend` (`friend_id`, `user_id`, `is_suscriber`, `privacy`, `created_at`, `friend_list_id`, `approved`)
VALUES (1, 2, 1, 0, '2012-08-13 18:16:11', 0, 1);
After you have done that your query should be more like the result you are after. Running this query:
select distinct u.id as `user_id`, u.username, f.id as `friend_id`, f.username as friend, s.*
from default_users as u
left join default_friend as df on df.user_id = u.id
left join default_users as f on f.id = df.friend_id
left join default_status as s on s.user_id = u.id
left join default_comment as c on c.status_id = s.status_id
order by s.status_id;
returns the following result set:
user_id username friend_id friend status_id message created_at privacy user_id is_reply device
1 admin 2 demo 1 dasdasdasdasdasd 2012-08-13 19:45:37 NULL 1 0
2 demo 1 admin 2 dasdasdasdasdasd 2012-08-13 19:46:03 NULL 2 0
1 admin 2 demo 3 dasdsad344hbvnbnhjhgjhjghjhj 2012-08-13 21:54:53 NULL 1 0
Is this anywhere near what you are looking for?
That's what GROUP BY
is used for. Get one row (per group). In this case, it will show all distinct user_id
values and for the rest of the columns, you can (have to) use aggregate functions like MIN()
, MAX()
, AVG()
, SUM()
as you will have more than one values per group and only one can be shown.
SELECT
user_id
, MIN(comment) AS comment -- it will show the first in alphabetical order
-- you could also use MAX()
FROM
tableX
GROUP BY
user_id ;
MySQL allows also the following unorthodox solution, that will return one (more or less random) comment per user:
SELECT
user_id
, comment
FROM
tableX
GROUP BY
user_id ;
This last query will not work but raise an error if the (stricter) ONLY_FULL_GROUP_BY
mode is enabled. In the recently released 5.7 version, this mode is the default and a new function, ANY_VALUE()
, is provided. For more details, see the MySQL Handling of GROUP BY
page. The query can be written now:
SELECT
user_id
, ANY_VALUE(comment) AS comment
FROM
tableX
GROUP BY
user_id ;
Note that with either the "unorthodox" version or using the recent ANY_VALUE()
function, if we add more columns in the SELECT
list, their values is not guaranteed to be from the same row, just from a row in the same group. The way they are selected is not exactly random, depends on the execution plan and the indexes used.
Best Answer
You can use the technique described in:
http://blog.sqlauthority.com/2014/03/09/mysql-reset-row-number-for-each-group-partition-by-row-number/
to mimic:
In your case that would be something like: