我在下面有以下查询,它在大多数情况下都有效,直到我注意到它导致了一个小问题。基本上,现有查询的作用是从我的“home_comments”表中选择所有信息,然后匹配 profile_img 表中的最大 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`
最佳答案
您可以使用 case 语句:
$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
关于mysql - SELECT 查询检查数据库之外的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40288431/