亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

下面是我的PHP代碼,如果單純一次查詢不能實現,那PHP應怎樣寫呢?

下面是我的PHP代碼,如果單純一次查詢不能實現,那PHP應怎樣寫呢?

烙印99 2023-04-15 17:13:50
有一個user表,表中有兩個字段分別是username和city,表中有3條條記錄。username city張三 北京張三 上海李四 北京如果只是查詢張三和李四各有多少人,可以通過下面語句查詢select username,city,count(*)from usergroup by username問:怎樣查詢在不同城市叫張三和李四的人各有多少個呢?我希望顯示的結果是:張三 共2人 北京1人 上海1人 ...李四 共1人 北京1人 上海0人 ...所以通過通過下面查詢是不可行的。這會導致出現重復行,而且也不能統計張三有多少人。select username,city,count(*)from usergroup by username,city張三 1 張三 1 李四 1我需要的結果是:張三 2 1 1李四 1 1 0==============================================================<?php$db = new MySQLi(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);$query = " SELECT username,  count( * )  FROM user GROUP BY username ")$result = $db->query($query);$num_rows = $result->num_rows;$num_cols = $result->num_fields;echo '<table>';for ($i=0;$i<$num_rows;$i++){ $rows = $result->fetch_assoc(); echo '<tr>'; foreach($rows as $cols){ echo '<td>'.$cols.'</td>'; } echo '</tr>'; }echo '</table>'; ?>
查看完整描述

2 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

先執行

select username, city, count(*) from user group by city, username;

搜出來的結果(簡寫):

[  0 => [
    username => name1,
    city => city1,
    count => 1
  ],  1 => [
    username => name1,
    city => city2,
    count => 2
  ],
  ...
]

假設結果保存在$rs變量里,使用php處理一下:

$user = [];foreach ($rs as $row) {    $name = $row['username'];    $city = $row['city'];    isset($user[$name]['total']) {        $user[$name]['total'] += $row['count'];
    } else {        $user[$name]['total'] = $row['count'];
    }    $user[$name]['detail'][$city] = $row['count'];
}

當然這是按我自己喜歡的結構存的,你也可以修改成你喜歡的結構。出來的結果如下(簡寫):

[  user1 => [    total => 3,
    detail => [      city1 => 1,
      city2 => 2,
      ...
  ],
  ...
]


查看完整回答
反對 回復 2023-04-17
?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

select
username,
count(*),
(select count(*) from user where username = a.username and city = '北京'),
(select count(*) from user where username = a.username and city = '上海')
from user a
group by username

如果城市很多的話,先select username,city,count(*) from user group by username,city查出每個人在每個城市中的人數,然后對結果集進行遍歷統計


查看完整回答
反對 回復 2023-04-17
  • 2 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號