简体   繁体   中英

grouping mysql results with joined table

I'm making a simple table with list of articles, another table of users, and another of articles the users liked:

articles table:

id, userId, title, article, date

users table

id, name, email, last_login

likes table:

id, user_id, article_id, dateLiked

My current query:

SELECT 
articles.id as aid, articles.userId, articles.title, articles.article, 
likes.user_id as uLiked, likes.article_id as articleLiked 
FROM articles 
LEFT JOIN likes ON articles.id = likes.article_id
WHERE userId= "10"

So, I want to get all of a user's articles, then in the while loop, I check to see if the user signed in matches that row in likes, and show it active if it is. If it's not, it still shows as inactive.Same thing if they're viewing someone else's article. They should see all articles, but on the ones they linked should be active.

while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

    if($row['uLiked'] == 30 && $currentArticleID = $row['articleLiked']){ $status = 'active'; } else { $status = 'inactive';  }

    echo '<div class="'.$status.'">'.$row['title'].'</div>';

}

The problem is that when the article gets liked, the post shows twice, but it is active both times. I tried grouping, but then when it groups, it shows the article once like I want, but nothing is active.

Hopefully I'm explaining it correctly, but I'm really stuck here. any ideas guys? I might be approaching this wrong..

If you are going to use group by then mysql group all rows in one row and for that mysql will only pick first row from grouped rows and other rows will be ignored.

So you have change some logic for that.

use GROUP_CONCAT mysql method for that .

SELECT 
articles.id as aid, articles.userId, articles.title, articles.article, 
CONCAT(',',GROUP_CONCAT(likes.user_id),',') as uLiked, likes.article_id as articleLiked 
FROM articles 
LEFT JOIN likes ON articles.id = likes.article_id
WHERE userId= "10" group by {which every you want};

After that you will get data like ,10,30,15, ( userid ) in uLiked parameter.

Now you can check by strpos method of string to identified login user.

while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

    if(strpos($row['uLiked'], ',30,') !== false && $currentArticleID = $row['articleLiked']){ $status = 'active'; } else { $status = 'inactive';  }

    echo '<div class="'.$status.'">'.$row['title'].'</div>';

}

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