简体   繁体   中英

Select approved comments and unapproved comments of current user MySQL PHP

I'm new to mysql and I have a problem with selecting data from mysql database:

$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";

This select, selects all approved comments from database, but also, in this select, I need all unapproved comments of $current_user_id,

Result must look like:

[all approved post comments] + [all unapproved post comments of $current_user_id]


not sure if this will really work, but just give a try and see. I can't test the query since we don't have the schema.

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

What I thought is select all the approved comments OR ( comments that are not approved, but from this user ). You might have to alter the query till you get what you really needed, I'm just giving you the idea, not the exact query. Hope this will help you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM