简体   繁体   English

如何选择字段并在SQL中为每个字段计数?

[英]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. 我有一个名为message的SQL表,我想从表中选择DISTINCT用户名,该表将向ID为($ uid)的收件人发送任何消息,并使用单行查询为每个发件人选择COUNT(message)

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. 我已经用参数占位符替换了内联PHP变量-请使用参数绑定来避免SQL注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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