php - 在 php、MySql 中从多个表创建报告

标签 php mysql

我们有四个表,其中分别包含以下数据,

1. tbl_user [user_id, user_name, user_email, user_country]
2. tbl_questions [survey_id, survey_question, posted_on]
3. tbl_answers [answer_id, question_id, answers]
4. tbl_survey_result [user_id, question_id, answer_id, timestamp]

我们希望根据这些数据生成 Excel 报告,如下图所示,

survey_result_dd_mm_yyyy.xls

sr_no | User_id | User_name | User_Email | User_Country | Question_1 | Question_2... ( n number of questions)
1     | 123456  | John Doe  |john@doe.in | India        | His Answer | Another Ans...

那么,我们如何使用mysql、php生成这个报告呢?

最佳答案

我会通过形成像这样的基本查询来获取用户 ID 来实现它:

select u.user_id from tbl_user u

然后,假设我们在 $users 变量中获取用户 ID 数据,我将在 foreach ($users as $user) 循环中运行以下查询:

select u.user_id, u.user_name, u.user_email, u.user_country, q.survey_question, a.answers from tbl_user u
inner join tbl_survey s on u.user_id = s.user_id
inner join tbl_answers a on a.answer_id = s.answer_id
inner join tbl_questions q on q.question_id = s.question_id
where u.user_id = %user
order by u.user_id, q.survey_id'

最后,将查询解析为用户问题数组。

导出到excel的问题已经被巴巴在https://stackoverflow.com/a/10424955/3986395中回答了我将在这里分享他的答案:

header("Content-Disposition: attachment; filename=\"demo.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
foreach ($array as $data)
{
    fputcsv($out, $data,"\t");
}
fclose($out);

最后,如果您有数百万用户,您可能不希望在 foreach 循环中运行查询,而是编写组合查询来获取所有用户数据。此查询将为您提供 user_id-answer 记录,并且您需要在 php 中添加额外的处理逻辑来将数据合并到所需的数组中

select u.user_id, u.user_name, u.user_email, u.user_country, q.survey_question, a.answers from tbl_user u
inner join tbl_survey s on u.user_id = s.user_id
inner join tbl_answers a on a.answer_id = s.answer_id
inner join tbl_questions q on q.question_id = s.question_id
where ..
order by u.user_id, q.survey_id

关于php - 在 php、MySql 中从多个表创建报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51146551/

相关文章:

php - 基本数据表 Ajax 配置不起作用

mysql - 在mysql中使用日期类型字段优化查询

php - 我如何允许用户下载存储在 webroot 之外的文件?

javascript - 在 HTML 下拉菜单中更改项目时激活文本框

php - 用PHP处理Apple Push Notification Service的device token的方法

mysql - 将相似的查询结果合并为一行

mysql - 如何使 MySQL INSERT 语句不区分大小写?

php - 我如何在 Laravel 5.2 中延迟工作?

php - 将中间件附加到所有方法

mysql - 根据不同区域的日期名称减去时间