简体   繁体   中英

How to select fields and count for each field in SQL?

I have an SQL table called messages I want to select DISTINCT user names from table who are sending any message to the recipient who had the id ($uid) and also select COUNT(message) for every sender, using a one line query.

I've tried this code:

$query="SELECT DISTINCT clientname,user_id,user1pic, COUNT("SELECT id FROM messages WHERE clientname=clientname) AS counted FROM messages WHERE receiver=$uid and status='unread' ";
$messages=mysqli_query($cnx,$query);
while($row=mysqli_fetch_array($cnx,$messages)){

echo '<a class="example" > '.$row['clieenter code herentname'].''.$row['counted'].'</a>' ;}
if(mysqli_num_rows($cnx,$messages)<=0){
    echo '<a class="example" href="#">You Have No Messages</a>' ;
}

Try the following:

SELECT 
  clientname,
  user_id,
  user1pic, 
  COUNT(1) AS counted 
FROM 
  messages 
WHERE 
  receiver=:uid 
  and status='unread'
Group by
  clientname,
  user_id,
  user1pic;

I have replaced your inline PHP variable with a parameter placeholder - please use parameter binding to avoid SQL injection.

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