所以这是我的查询
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) ""
}
答案 0 :(得分: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
。
答案 1 :(得分: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。