我有以下查询,除了一件事之外,它运行得很好。它检查个人资料图像是否不在 profile_img
中所选用户的数据库,如果没有,它会提供默认图像。再说一遍,这很好。我的问题是,如果用户没有个人资料 img 那么我无法访问他们的 user_id
因为某些原因。不过,他们的用户名是正确的。但是,如果用户确实有 profile_img,则链接 echo '<a href="profile?user='.$comment_user_id.'">
,工作得很好。
任何人都知道如何在没有 profile_img 的情况下让其为用户工作?
SELECT c. *, PI.user_id, case when p.img <> '' and p.img is not null then p.img else 'profile_images/default.jpg' end img
FROM home_comments AS c
LEFT JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
LEFT JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
我试图用它来调用它的代码
$comment_user_id = $comment_row['user_id'];
$comment_username = $comment_row['username'];
echo '<a href="profile?user='.$comment_user_id.'"><div class="comment-post-username">'.$comment_username. '</div></a>';
数据库表
home_comments
CREATE TABLE `home_comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`username` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`comment` text COLLATE utf8_unicode_ci NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
)
profile_img
CREATE TABLE `profile_img` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`img` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
)
最佳答案
您正在使用 PI.user_id 来获取用户 ID,但这是从左连接到图像的字段,因此它将为空。
请使用 home_comments 中的 user_id。
如果您只是取出 PI,那么 C 中的通配符应该起作用或使用字段名称列表(总是更好。
SELECT C.user_id, -- or C.*,
case when p.img <> '' then p.img else 'profile_images/default.jpg' end img
FROM home_comments AS c
LEFT JOIN (
SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id
) PI on PI.user_id = c.user_id
LEFT JOIN profile_img p on PI.user_id = p.user_id and PI.id = p.id
ORDER BY c.id DESC
测试 2
SELECT C.*,
case when p.img <> '' and p.img is not null then p.img else 'profile_images/default.jpg' end img
FROM home_comments AS c
LEFT JOIN (
SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id
) PI on PI.user_id = c.user_id
LEFT JOIN profile_img p on PI.user_id = p.user_id and PI.id = p.id
ORDER BY c.id DESC
关于php - SELECT 查询案例导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746969/