所以我有一个网页,显示图像和相关信息,并且我还有三个表格。
IMAGES USERS COMMENTS
id user_id id
user_id username user_id
username password comment
title isadmin date
image (location) points
description signup_date
points email
category city
bio
profile_image
我需要使用图像和评论表中的所有信息。但我还需要检索发布评论和图像的用户的 profile_image。我不知道如何做到这一点:这是我到目前为止所拥有的。
$conn = new PDO ("mysql:host=localhost;dbname=project", "root", "pass");
$stmt = $conn->prepare("
SELECT images.*, users.profile_image, comments.*
FROM (images.id JOIN comments ON images.id = comments.id)
LEFT JOIN users
ON images.user_id = user.profile_image
");
我很接近吗?或者在这里尝试不可能的事情!?
最佳答案
这比你想象的要简单得多:)
这些表并不是不相关的,它们都有相同的键 - user_id
,这就是您加入它们的方式。
您的查询应如下所示:
SELECT images.*, users.profile_image, comments.*
FROM images
JOIN users ON images.user_id = users.user_id
JOIN comments ON comments.user_id = users.user_id AND images.id = comments.id
这是假设 images.id
和 comments.id
匹配(我怀疑它们不匹配 - 但您没有向我们提供足够的信息)
查看您的表结构,评论和图像似乎没有任何联系,因此可以单独查询它们以避免重复和困惑的数据
---更新---
假设您已将 image_id
添加到评论
,这是您的查询:
SELECT images.*, users.profile_image, comments.*
FROM images
LEFT JOIN users ON images.user_id = users.user_id
LEFT JOIN comments ON comments.user_id = users.user_id AND images.id = comments.image_id
LEFT JOIN 的作用是返回不一定有“用户”或“评论”与之关联的“图像”。
关于php - 如何连接三个具有不相关数据的MySQL表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833206/