2017-05-07 83 views
0

所以我有一个显示图像和信息的网页,我也有三张表。如何使用不相关的数据连接三​​个MySQL表?

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 
"); 

我关闭了吗?或在这里尝试不可能的!?

+0

所以你的目标是让所有与它的用户的信息和图像的意见吗? – Beginner

+0

如果你问我,我会得到一个新的查询意见。第一个查询获取图像+用户数据第二个查询获取注释和用户数据 –

+0

我不认为这三个表完全不相关;用户的ID肯定出现在每个表格中。但我不清楚我们如何将评论与其他两张表相关联。它几乎看起来好像某个外键丢失了。 –

回答

1

这是一个简单多了,那么你会觉得:)

表不无关系,它们都具有相同的密钥 - 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.idcomments.id比赛(我怀疑他们不这样做 - 但你并没有给我们足够的信息)

看着你的表结构,评论和图像似乎没有连接,所以也许单独查询它们以避免重复&混淆数据

--- UPDATE ---

假设你已经添加到image_idcomments你查询:

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所做的就是回报“图像”不一定有“用户”或“意见”连接到他们。

+0

对缺乏信息的道歉,会添加一个名为image_id的列可以链接到图像的ID?这意味着ID匹配,但使用不同的名称 –

+0

如果您可以添加注释匹配的图像的image_id,那很完美,您可以编写一个干净的查询 –

+0

我想我在这里迷惑自己,所以我应该向评论表添加一个image_id。我是否需要将image_id添加到图像表中,以便我可以加入它们?或者我可以将评论中的图片ID与image_id链接起来? –

0

我想这将这样的伎俩:

SELECT i.*, u.profile_image, c.* 
FROM images i 
LEFT JOIN comments c ON i.user_id = c.user_id 
LEFT JOIN users u ON i.user_id = u.user_id 
0

我认为它是:

> SELECT images.*, users.profile_image, comments.* 
>  FROM images 
>  INNER JOIN users ON images.user_id= users.user_id 
>  INNER JOIN comments ON users.user_id= comments.user_id 
相关问题