如何在我的 mySQL 中以正确的方式使用 concat 来获取注册最多的工具的百分比

How to use concat the right way in my mySQL to get the percentages of which tools have been registered the most

我想要一些统计数据并计算在我的数据库的所有注册中哪些工具被选择最多的百分比

这是我的两个 table:

$table_registration = $wpdb->prefix . 'registration';
$table_tools = $wpdb->prefix . 'tools';

wp_registration table:

CREATE TABLE $table_registration
(
    reg_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    dato date,
    billedeURL VARCHAR(80) NOT NULL,
    fiske_vaegt DECIMAL( 2,1 ) NOT NULL,
    fiske_laengde INT NOT NULL,         
    reg_user_id BIGINT UNSIGNED NOT NULL,
    reg_tools_id INT UNSIGNED NOT NULL

    PRIMARY KEY (reg_id),
    FOREIGN KEY (reg_user_id) REFERENCES wp_users(id),
    FOREIGN KEY (reg_tools_id) REFERENCES $table_tools(tools_id) 
)

wp_tools table:

CREATE TABLE $table_tools
(
    tools_id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    tools_navn CHAR (20),

    PRIMARY KEY (tools_id)
)

我一直在尝试创建正确的 mysql 但没有成功,所以这就是我到目前为止一直在做的事情。

select l.*, concat(round(100 * count(t.reg_tools_id) / t2.cnt,0),'%')
from wp_registration l
left join wp_tools t on l.toolss_id = t.reg_id
cross join 
    (select count(*) cnt
     from wp_registration
     where reg_tools_id = 1) t2
group by l.reg_id;

但它告诉我每个工具都被使用了 50% 的次数。这显然是错误的我有三种工具可供用户选择,现在有 1 - 两票和 2 - 九票和 3 - 两票总共有 13 个注册

希望我明白你需要什么!

SELECT 
    tools.tools_id,
    ((COUNT(*) / (SELECT COUNT(*) FROM registration)) * 100) AS percent  
FROM 
    registration 
JOIN 
    tools ON registration.reg_tools_id = tools.tools_id
GROUP BY 
    tools.tools_id
ORDER BY 
    percent DESC 
LIMIT 1

一些评论:

  • 尽量写得纯sql
  • 这个问题不需要 php 标签
  • 减少不必要部分的代码
  • 使用您使用的编程语言中的 concat 和 round 函数,而不是 SQL(我认为您在这里使用的是 php,所以查询然后得到结果并应用round 和 php 指令中的 concat)