2013-04-09 60 views
1

因此,這裏是我的查詢加入查詢顯示僅基於一個比賽結果

SELECT `c`.`location`, `c`.`id`, `c`.`user_id`, `c`.`date`, `c`.`attachment`, 
`ud`.`first_name`, `ud`.`last_name`, 
`a`.`file_name`, `a`.`folder_name`, `a`.`server_key`, `a`.`type` FROM `content` 
AS `c` INNER JOIN `users_details` AS `ud` ON ud.user_id = c.user_id INNER JOIN 
`attachments` AS `a` ON c.id = a.content_id WHERE (c.location = 'New York') 

我期待還包括從附件表中的結果數據,問題是,從沒有任何數據行表content有一個附件,如果一個帖子有一個附件,它會在行附件的內容表中保存爲1,如果沒有附件則保存爲0。

現在的問題是,我的查詢只顯示有附件的數據,我猜這個問題來自與附件表的連接。

那麼我該如何做到這一點,所以我有以下輸出:將數據合併在一起,以顯示上傳的帖子,也沒有這樣做,還顯示附件表中的數據與上傳的數據。有點像這樣:

[0] => array(11) { 
    ["location"] => string(15) "New York" 
    ["id"] => string(2) "25" 
    ["user_id"] => string(1) "1" 
    ["date"] => string(10) "1364348772" 
    ["attachment"] => string(1) "1" 
    ["first_name"] => string(8) "John" 
    ["last_name"] => string(7) "Doe" 
    ["file_name"] => string(36) "c2638acdac24dc2efe4e5971db5f4cc5.jpg" 
    ["folder_name"] => string(13) "5133b99030ac4" 
    ["server_key"] => string(1) "1" 
    ["type"] => string(1) "1" 
    } 
    [1] => array(11) { 
    ["location"] => string(15) "New York" 
    ["id"] => string(2) "26" 
    ["user_id"] => string(1) "1" 
    ["date"] => string(10) "1364348812" 
    ["attachment"] => string(1) "0" 
    ["first_name"] => string(8) "John" 
    ["last_name"] => string(7) "Doe" 
    ["file_name"] => string(36) "" 
    ["folder_name"] => string(13) "" 
    ["server_key"] => string(1) "" 
    ["type"] => string(1) "" 
    } 
+1

我想我需要做一個左連接 – Uffo 2013-04-09 00:16:15

回答

2

這似乎是你只需要LEFT OUTER JOIN附件表是這樣的:

SELECT 
    `c`.`location`, 
    `c`.`id`, 
    `c`.`user_id`, 
    `c`.`date`, 
    `c`.`attachment`, 
    `ud`.`first_name`, 
    `ud`.`last_name`, 
    `a`.`file_name`, 
    `a`.`folder_name`, 
    `a`.`server_key`, 
    `a`.`type` 
FROM `content` AS `c` 
INNER JOIN `users_details` AS `ud` 
    ON ud.user_id = c.user_id 
LEFT OUTER JOIN `attachments` AS `a` 
    ON c.id = a.content_id 
WHERE c.location = 'New York' 

OUTER JOIN無論將返回所有結果以是否有a.content_id匹配到c.id 。附件表中的那些選定字段將顯示爲NULL

+0

是的,這是解決方案,我太累了謝謝你! – Uffo 2013-04-09 00:17:55

1

嘗試使用LEFT OUTER JOIN:

SELECT `c`.`location`, `c`.`id`, `c`.`user_id`, `c`.`date`, `c`.`attachment`, 
`ud`.`first_name`, `ud`.`last_name`, 
`a`.`file_name`, `a`.`folder_name`, `a`.`server_key`, `a`.`type` FROM `content` 
AS `c` INNER JOIN `users_details` AS `ud` ON ud.user_id = c.user_id LEFT OUTER JOIN 
`attachments` AS `a` ON c.id = a.content_id WHERE (c.location = 'New York') 

有一個很好的Wikipedia page about joins