SELECT查询检查数据库之外的内容

时间:2016-10-27 15:19:46

标签: mysql sql

我在下面有以下查询,它大部分都有效,直到我发现它引起了轻微的问题。基本上现有的查询是从我的'home_comments'表中选择所有信息,然后匹配profile_img表中的max id并获取该图像。

我遇到的问题是并非所有用户都拥有此数据库中的个人资料图片。对于默认图像,我使用静态图像。那么,无论如何我可以检查用户是否有profile_img,如果没有使用它?

$default_profile_img = '<img class="home-profile-pic" src="profile_images/default.jpg">';

查询:

$select_comments_sql = "
        SELECT c. *, p.user_id, p.img
        FROM home_comments AS c
        INNER JOIN (SELECT max(id) as id, user_id 
                    FROM profile_img 
                    GROUP BY user_id) PI
          on PI.user_id = c.user_id
        INNER JOIN profile_img p
          on PI.user_id = p.user_id
         and PI.id = p.id
        ORDER BY c.id DESC

编辑:更新了SQL

$select_comments_sql = "
    //SELECT c. *, p.user_id, p.img
    SELECT c. *, PI.user_id, case when PI.img <> '' and PI.img is not null then PI.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
";

错误:

[27-Oct-2016 13:29:56 America/Chicago] PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '//SELECT c. *, p.user_id, p.img
            SELECT c. *, PI.user_id, case when PI.img <> ' at line 1' in /home4//public_html/.com/account/ajax-php/comment-retrieve.php:36`

2 个答案:

答案 0 :(得分:3)

您可以使用案例陈述:

$select_comments_sql = "
    SELECT c. *, p.user_id, case when p.img <> '' and p.img is not null then p.img else 'my-default.png' end img
    FROM home_comments AS c
    INNER JOIN (SELECT max(id) as id, user_id 
                FROM profile_img 
                GROUP BY user_id) PI
      on PI.user_id = c.user_id
    INNER JOIN profile_img p
      on PI.user_id = p.user_id
     and PI.id = p.id
    ORDER BY c.id DESC

答案 1 :(得分:0)

尝试这种方式,我假设你使用mysqli$row返回关联数组。

$row = mysqli_fetch_assoc($select_comments_sql);
if(!empty($row['profile_image_field_name'])){
    $default_profile_img = '<img class="home-profile-pic" src="profile_images/'.$row['profile_image_feild_name'].'">';
}else{
    $default_profile_img = '<img class="home-profile-pic" src="profile_images/default.jpg">';
}