我正在尝试从关系表中检索数据,以显示来自其中的ID的信息。
我有3张桌子:
users
id
username
email
password
projects
id
name
fave_project
id
user_id
project_id
我想查询关系表,以显示与我通过会话存储在变量中的特定用户ID相关联的项目的名称。
在这里,我的SQL查询适用于某一点,但是重复结果:
$sql = "SELECT fav_project.project_id, fav_project.user_id, project.id, project.name
FROM fav_project
JOIN users
JOIN project
ON fav_project.project_id = project.id
WHERE fav_project.user_id = $userId";
更新
以下是我的输出示例:
array(4) { ["project_id"]=> string(2) "10" ["user_id"]=> string(1) "7" ["id"]=> string(1) "8" ["name"]=> string(12) "Test Project" } array(4) { ["project_id"]=> string(2) "12" ["user_id"]=> string(1) "7" ["id"]=> string(1) "8" ["name"]=> string(15) "Awesome project" } array(4) { ["project_id"]=> string(2) "10" ["user_id"]=> string(1) "7" ["id"]=> string(1) "7" ["name"]=> string(12) "Test Project" } array(4) { ["project_id"]=> string(2) "12" ["user_id"]=> string(1) "7" ["id"]=> string(1) "7" ["name"]=> string(15) "Awesome project" }
答案 0 :(得分:1)
如果用户有多个项目,那么您将看到重复的用户ID(每个用户ID都有不同的项目ID)。如果您希望每个用户ID占一行,则必须使用group_concat
之类的分组功能。以下是一个例子
SELECT u.id, GROUP_CONCAT(p.name)
FROM users u JOIN fave_projects fp on u.id = fp.user_id
JOIN projects p ON fp.project_id = p.id
WHERE u.id = $userId
GROUP BY u.id;
Here是group_concat
的文档。
<强>更新强>
如果您只想看项目,那么下面应该这样做:
SELECT DISTINCT p.id, p.name
FROM users u JOIN fave_projects fp on u.id = fp.user_id
JOIN projects p ON fp.project_id = p.id
WHERE u.id = $userId;
<强>更新强>
要使现有查询有效,您需要向其添加DISTINCT
,例如:
SELECT DISTINCT fav_project.project_id, fav_project.user_id, project.id, project.name
FROM fav_project
JOIN users
JOIN project
ON fav_project.project_id = project.id
WHERE fav_project.user_id = $userId"