Reputation: 8990
(
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM relationships r
JOIN notes m ON m.user_id = r.leader
JOIN user u ON r.leader = u.user_id
WHERE r.listener ='2'
)
UNION ALL
(
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM notes m
JOIN user u ON m.user_id = u.user_id
WHERE u.user_id ='2'
)
WHERE dt > '2010-09-20_131830'
ORDER BY dt DESC
what this deos is it queries the user(loggedin), people they follow and retrives thier messages. tables are shown below,!
what i want to add to this query, is also the user(loggedin) updates aswell. but obviously the user deosnt follow himself. whats the best way i can do this!!
user_id | username
-------------------
1 | solomon
2 | muna
id user_id| message
---------------------------------------
1 1 | this is my first message
2 1 | this is my second message
3 2 | this is muna message
leader | follower
------------------
1 | 2
Upvotes: 1
Views: 95
Reputation: 344581
The most obvious solution would be to UNION ALL
your query, with another similar query that retrieves the messages of the logged in user. Something like this:
(
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM relationships r
JOIN notes m ON m.user_id = r.leader
JOIN user u ON r.leader = u.user_id
WHERE r.listener ='".$_SESSION['user_id']."'
)
UNION ALL
(
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM notes m
JOIN user u ON m.user_id = u.user_id
WHERE u.user_id ='".$_SESSION['user_id']."'
);
UPDATE:
Following the updated query, you cannot have a WHERE
clause out there. You should either have a separate WHERE
for each query, or else use a derived table like this:
SELECT *
FROM
((
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM relationships r
JOIN notes m ON m.user_id = r.leader
JOIN user u ON r.leader = u.user_id
WHERE r.listener ='".$_SESSION['user_id']."'
)
UNION ALL
(
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM notes m
JOIN user u ON m.user_id = u.user_id
WHERE u.user_id ='".$_SESSION['user_id']."'
)) d
WHERE d.dt > '2010-09-20_131830'
ORDER BY d.dt DESC;
Upvotes: 2
Reputation: 19012
How about this:
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM notes m
INNER JOIN user u
ON m.user_id = u.user_id
WHERE (m.user_id = '".$_SESSION['user_id']."'
OR m.userID IN (
SELECT r.leader
FROM relationships r
WHERE r.listener ='".$_SESSION['user_id']."'))
Upvotes: 2