SELECT查询案例导致问题

时间:2016-11-22 16:28:40

标签: php mysql sql hyperlink case

我有以下查询,除了一件事情以外完美无缺。它会检查配置文件图像是否不在所选用户的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`)
)

2 个答案:

答案 0 :(得分:2)

您正在使用PI.user_id获取用户ID,但这是从左连接到图像的字段,因此它将为null。

改为使用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

TEST 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

答案 1 :(得分:0)

我认为这已足够:

SELECT c.*, PI.user_id,
       (case when p.img <> '' then p.img else 'profile_images/default.jpg'
        end) as img

请注意,NULL几乎无法进行任何比较,包括<>