[英]MySQL-how to query to get all records and distinct count of specific column in single query
我有三個字段的表。
id name place
1 A x
2 A v
3 B z
4 A a
我已經有這樣的查詢,
select Id
, Place
from tbname
where Name like '" . mysql_real_escape_string( $name, $sql ) . "'
這也將與'%'進行通配符匹配
現在,我想要的是在上述查詢中對“名稱”字段的不同值進行計數,而不影響先前的結果。
如果通配符與“名稱”字段中的所有值匹配,則計數為2。
如果我願意
select Id
, count(distinct Name) as count
, Place from tbname
where Name like '" . mysql_real_escape_string( $tidbit, $sql ) . "'
這將返回,
Id:1
count:2
Place:x
但是我想要所有的比賽以及計數,
Id:1,2,3,4
count:2
Place:x,y,z,q
有沒有辦法在單個查詢中執行此操作,或者在sql或php中有任何函數?
請幫助我找出這個問題。
提前致謝。
我認為
select Res1.id,Res1.cnt,Res2.place from (select id,count(distinct Name) cnt
from tbname groupby id) res1 inner join
select distinct id ,place from tbname group by id ) res2 on
res1.id=res2.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.