I have run into some troubles while writing a query for MySQL. I don't know how to describe my problem well enough to search the web for it, so sorry if my question is stupid.
I have 3 tables:
CREATE TABLE posts( id INT, author INT );
CREATE TABLE users( id INT, nick varchar(64) );
CREATE TABLE groups( id INT, name varchar(64) );
CREATE TABLE membership (user INT, group INT, date INT ) ;
Membership contains info about users that have joined some groups. "Date" in the membership table is the time when a user joined that group.
I need a query which will return a post, its author's nick and the name of the group with the least joining date.
All I have currently is:
SELECT p.id, u.nick, g.name
FROM posts AS p
LEFT JOIN users AS u ON u.id = p.author
LEFT JOIN membership AS m ON m.user = p.author
LEFT JOIN groups AS g ON g.id = m.group
WHERE 1;
but of course it returns a random group's name, not the one with earliest joining date.
I also tried the following variant:
SELECT p.id, u.nick, g.name
FROM posts AS p
LEFT JOIN users AS u ON u.id = p.author
LEFT JOIN
(SELECT * FROM membership WHERE 1 ORDER BY date ASC)
AS m ON m.user = p.author
LEFT JOIN groups AS g ON g.id = m.group
WHERE 1;
but it gave me same result.
I would appreciate even pointers to where I could start, because at the moment I have no idea what to do with it.