我有三个简单的表格:用户,个人资料和观看的内容,其中包含用户的ID和观看的电影标题.
并且下面的脚本显示与所观察表中的不同用户匹配的值:
$id = $_SESSION['id'];
echo "my id: $id\n";
$movies = mysqli_query($connect, "SELECT w1.users_id AS user1,
w2.users_id AS user2,
COUNT(w2.watched) AS num_movies,
GROUP_CONCAT(w2.watched ORDER BY w2.watched) AS movies
FROM watched w1
JOIN watched w2 ON w2.watched = w1.watched AND w2.users_id != w1.users_id
WHERE w1.users_id = $id
GROUP BY user1, user2");
while ($row = $movies->fetch_assoc()) {
echo "matched with id {$row['user2']} {$row['num_movies']} times on titles {$row['movies']}\n";
}
输出:
my id = `1`;
matched with id `2` 2 times on titles `movie2`, `movie1`;
matched with id `3` 1 times on titles `movie1`;
但是我还想显示用户的姓名,个人资料等.
像在此查询中一样:SELECT * FROM profile INNER JOIN users ON profile.users_id = users.id
如何合并第一个和第二个查询?
尝试过:
SELECT *, w2.watched,
COUNT(w2.watched) AS num_movies,
GROUP_CONCAT(w2.watched order by w2.watched) as movies
FROM profile AS p
JOIN users AS u ON p.users_id = u.id
LEFT JOIN watched AS w ON w.users_id = u.id and w.watched=w2.watched
WHERE u.id != $id
GROUP BY w.users_id
但它不起作用.
解决方法:
尝试这个
SELECT w1.users_id AS user1,u.name as name, p.*, u.*, w2.users_id
AS user2, COUNT(w2.watched) AS num_movies,
GROUP_CONCAT(w2.watched ORDER BY w2.watched) AS movies
FROM watched w1
JOIN watched w2 ON w2.watched = w1.watched
AND w2.users_id != w1.users_id
JOIN users u ON u.id=w1.users_id
JOIN profile p ON p.users_id=w1.users_id
WHERE w1.users_id =1 GROUP BY user1, user2