2017-05-07 89 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 
相關問題