选择左连接

时间:2014-10-07 12:56:03

标签: php mysql sql

我的php会话:

$get_user = $_SESSION['id']; //id of the user that logged in

我的查询是:

$query_select = "SELECT i.users_id,s.seen, CONCAT_WS(' ', i.users_fname, i.users_lname)
AS full_name
FROM tbl_request AS f
LEFT JOIN tbl_usersinfo AS i ON i.users_id = f.user_id
LEFT JOIN tbl_status AS s ON s.user_id = f.user_id 
WHERE (f.user_id = $get_user || f.another_user = $get_user) && f.status = 'accepted'
GROUP BY full_name ORDER BY seen DESC

tbl_request:

user_id    another_user   status
1               2        'accepted'
1               5        'accepted'
3               1         'waiting'
4               1         'accepted'  

tbl_usersinfo

users_id    users_fname       users_lname
1              michael            jackson
2              michael            jordan
3              bat                man
4              will               smith
5              sean               kingston

tbl_status

user_id     seen
1           'online'
2            'offline'
3            'online'
4            'online'
5            'offline'

假设会话等于1,此查询将导致:

users_id   full_name     seen
4          will smith    online

它应该是:

 users_id   full_name            seen
    2       michael jordan       offline
    4       will smith           online
    5       sean kingston        offline

我想选择所有等于“已接受”的状态,但上面的查询仅在会话等于another_user时显示。我希望我的查询灵活。例如,当session等于user_id时,它应该选择another_user,因为那是他朋友的id。

1 个答案:

答案 0 :(得分:1)

问题是,在LEFT JOIN中,您始终与f.user_id进行比较,但只有f.user_id位于$get_user时才应another_user }列...以及其他方式也一样......我建议你重新制作完成你的查询...

有很多方法可以做到这一点,但使用UNION可能更简单:

SELECT i.users_id,s.seen, CONCAT_WS(' ', i.users_fname, i.users_lname)
AS full_name
FROM tbl_request AS f
LEFT JOIN tbl_usersinfo AS i ON i.users_id = f.another_user
LEFT JOIN tbl_status AS s ON s.user_id = f.another_user 
WHERE f.user_id = $get_user && f.status = 'accepted'
UNION
SELECT i.users_id,s.seen, CONCAT_WS(' ', i.users_fname, i.users_lname)
AS full_name
FROM tbl_request AS f
LEFT JOIN tbl_usersinfo AS i ON i.users_id = f.user_id
LEFT JOIN tbl_status AS s ON s.user_id = f.user_id 
WHERE f.another_user = $get_user && f.status = 'accepted'
GROUP BY full_name ORDER BY seen DESC