假设有一首歌曲和一首歌,我们想知道喜欢同一首歌的所有朋友(直接朋友和朋友):
这就是我们这样做的方式:
public function get_song_mates($uid, $song_id, $current_only = true, $limit = PHP_INT_MAX)
{
$sql = "SELECT *
FROM (
(
SELECT users . * , '1st' AS `level`, 1 AS `level_i`
FROM songs
JOIN users ON users.id = songs.user_id
JOIN friends AS my_friend ON my_friend.fid = users.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."')
UNION (
SELECT second_friend . * , '2nd' AS `level`, 2 AS `level_i`
FROM songs
JOIN users AS second_friend ON second_friend.id = songs.user_id
JOIN friends ON friends.uid = second_friend.id
JOIN users AS first_friend ON first_friend.id = friends.fid
JOIN friends AS my_friend ON my_friend.fid = first_friend.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."'
AND second_friend.id NOT IN
(
SELECT users.id
FROM songs
JOIN users ON users.id = songs.user_id
JOIN friends AS my_friend ON my_friend.fid = users.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."'
)
) ORDER BY `level_i` ASC, firstname, lastname
) AS friend
GROUP BY id ORDER BY `level_i`";
$users = $this->getFromSql($sql);
return $users;
}
但请注意我们必须添加:
AND second_friend.id NOT IN...
防止显示与直接朋友和朋友的朋友相同的用户..我很确定我需要使用GROUP BY,但我无法使用正确的语法。这里有什么线索吗?
- 编辑 -
friends(uid, fid)
songs(id, user_id, song_id)
users(id, frist_name, last_name)
答案 0 :(得分:0)
修正如下:
公共函数get_song_mates($ uid,$ song_id,$ current_only = true,$ limit = PHP_INT_MAX) {
$sql = "SELECT DISTINCT *
FROM (
(
SELECT users . * , '1st' AS `level`, 1 AS `level_i`
FROM songs
JOIN users ON users.id = songs.user_id
JOIN friends AS my_friend ON my_friend.fid = users.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."')
UNION (
SELECT DISTINCT second_friend . * , '2nd' AS `level`, 2 AS `level_i`
FROM songs
JOIN users AS second_friend ON second_friend.id = songs.user_id
JOIN friends ON friends.uid = second_friend.id
JOIN users AS first_friend ON first_friend.id = friends.fid
JOIN friends AS my_friend ON my_friend.fid = first_friend.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."'";
$users = $this->getFromSql($sql);
return $users;
}