我是mysql的新手,我在从mysql数据库中选择数据时遇到了问题:
$post_id = 3;
$current_user_id = 1;
$query = "SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND `comments`.`status` = 1
AND `users`.`status` = 1
ORDER BY `comments`.`date` desc";
此选择,从数据库中选择所有已批准的注释,但在此选择中,我需要$ current_user_id的所有未批准的注释,
结果必须如下:
[所有已批准的帖子评论] + [所有未批准的$ current_user_id帖子评论]
答案 0 :(得分:2)
不确定这是否真的有效,但只是试试看。我无法测试查询,因为我们没有架构。
SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND (
(`comments`.`status` = 1 AND `users`.`status` = 1)
OR
( `comments`.`status` = 0 AND `users`.`id`= '$current_user_id' )
)
ORDER BY `comments`.`date` desc
我的想法是选择所有approved comments
OR(未经批准但来自此用户的评论)。你可能不得不改变查询,直到你得到你真正需要的东西,我只是给你这个想法,而不是确切的查询。希望这会对你有所帮助。
答案 1 :(得分:1)
SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND `comments`.`status` = 1
AND `users`.`status` = 1
UNION ALL
SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND `comments`.`status` = 0
AND `users`.`id` = '$current_user_id'
ORDER BY `comments`.`date` desc