我正在尝试为Wordpress创建短代码。我想通过{answer}来显示DISTINCT
,而COUNT
显示来自'answer'的总数。
如果你在我的代码中找到foreach
,我不知道如何回显计数,因为我正在使用函数来返回值。
目前我正在使用count($data->answer);
。
表:wp_events_answer
╔════╦══════════════╦════════════╗
║ id ║ answer ║question_id ║
╠════╬══════════════╬════════════╣
║ 1 ║ Maybank ║ 12 ║
║ 2 ║ Maybank ║ 12 ║
║ 3 ║ Maybank ║ 12 ║
║ 4 ║ CIMB ║ 12 ║
╚════╩══════════════╩════════════╝
我希望的结果是
╔════╦══════════════╦════════════╗
║ No ║ Bank ║ Total ║
╠════╬══════════════╬════════════╣
║ 1 ║ Maybank ║ 2 ║
║ 2 ║ CIMB ║ 1 ║
╚════╩══════════════╩════════════╝
我目前的结果
╔════╦══════════════╦════════════╗
║ No ║ Bank ║ Total ║
╠════╬══════════════╬════════════╣
║ 1 ║ Maybank ║ 1 ║
║ 2 ║ Maybank ║ 1 ║
║ 3 ║ Maybank ║ 1 ║
║ 4 ║ CIMB ║ 1 ║
╚════╩══════════════╩════════════╝
这是我的代码:
$sql= "
SELECT *, count(*)
FROM wp_events_answer
INNER JOIN wp_events_attendee ON wp_events_attendee.registration_id= wp_events_answer.registration_id
WHERE question_id=12 AND event_id='$eventid' GROUP by answer
";
$datas= $wpdb->get_results($sql);
$num_rows = $wpdb->num_rows;
if ($num_rows > 0)
{
$result .= '<table id="attendeeList">
<thead>
<tr>
<th width="10%" scope="col">No.</th>
<th width="70%" scope="col">Group Name</th>
<th width="20%" scope="col">Total</th>
</tr></thead>';
$number = 1;
foreach ($datas as $data) {
$result .= '<tbody>';
$result .= '<tr>';
$result .= '<td>';
$result .= $number++;
$result .= '</td>';
$result .= '<td>';
$result .= $data->answer;
$result .= '</td>';
$result .= '<td>';
$result .= count($data->answer); //i have no idea how to print total this
$result .= '</td>';
$result .= '</tr>';
}
$result .= '</table>';
return $result;
}
else
{ return 'There is no group'; } }
答案 0 :(得分:1)
SQL:
SELECT answer, count(answer) as total
FROM wp_events_answer
INNER JOIN wp_events_attendee
ON wp_events_attendee.registration_id= wp_events_answer.registration_id
WHERE question_id=12
AND event_id='$eventid'
GROUP BY
answer
PHP:
....
$result .= $data->answer;
$result .= '</td>';
$result .= '<td>';
$result .= $data->total;
$result .= '</td>';