我试图用mysql计算一个列的最多选择值,但我不知道如果这是可能的,或者如果我还需要使用php ...
所有值都是整数形式1到12的整数,它们是在前端进行的选择的id,而表(id:table)如下所示:
id | value_1 (int) | value_2 (int) | value_3 (int)
编辑:
有了这个,我可以获得最多选择的'value_1'列:
SELECT value_1, count( * ) total
FROM table
GROUP BY value_1
ORDER BY total DESC
LIMIT 1
如何在单个SQL语句中获取树列(value_1 | value_2 | value_3)中所有选中的最多值?
在重复的quiestion链接之后,我也尝试了这个,但它返回一个错误:
select value_1, count(*) total
from (
select @r := if(total>@r,total,@r) maxcount, value_1, total
from (select @r:=0) initvars, (
select value_1, count(*) total
from table
group by value_1
) X ) Y
where total = @r
MYSQL ERROR : #1140 - Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
答案 0 :(得分:0)
SELECT id,
COUNT(val1)As 'First Value',
COUNT(val2)As 'Second Value',
COUNT(val3)As 'Third Value'
FROM alez
GROUP BY id
ORDER BY id DESC
选择最高编号的ID将首先出现。然后,它们将根据最多选择的数字从最高到最低排序。
答案 1 :(得分:0)
只是向读过这篇文章的用户澄清我设法做到了但是也使用了PHP。只用一次MYSQL句子就可以了,但我无法弄清楚如何做到这一点:
$array_sql = array("value_1", "value_2", "value_3");
//Loop
foreach($array_sql as $val){
$SQL = "
SELECT $val, count( * ) total
FROM table
GROUP BY $val
ORDER BY total DESC
LIMIT 1
";
${'result_'.$val} = mysql_query($SQL) or die(mysql_error());//$result_mvp
}
//results for value_1
$row_1 = mysql_fetch_array($result_value_1);
$val1 = $row_1['total']; // Most selected option for value_1
//results for value_2
$row_2 = mysql_fetch_array($result_value_2);
$val2 = $row_2['total']; // Most selected option for value_2
//results for value_3
$row_3 = mysql_fetch_array($result_value_3);
$val3 = $row_3['total']; // Most selected option for value_3