0

我正在尝试使用此 JSON 数据编写一个高效的 mySQL INSERT 查询(为清楚起见,转换为 JSON):

[
    {
        "job": "Avocado Books Binding",
        "tasks": [
            "Finish collating the signatures",
            "Fix perfect binders",
            "Fold signatures"
        ]
    },
    {
        "job": "Prepress Workflow Development",
        "tasks": [
            "Research new proofing machines",
            "Find free proofing software"
        ]
    }
]

生成的表结构将是(使用此数据)

Table: Jobs
job_id   job_title
1        Avocado Books Binding
2        Prepress Workflow Development

Table: Tasks
task_id   task_description                    job_id
1         Finish collating the signatures     1
2         Fix perfect binders                 1
3         Fold signatures                     1
4         Research new proofing machines      2
5         Find free proofing software         2

作业和任务通过 job_id 关联的位置。

我也在尝试编写一个 SELECT 查询,以一种高效的方式获取这些数据。

非常感谢任何帮助、参考或建议。

更新:

结构为 PHP 数组

Array
(
    [0] => Array
        (
            [job] => Avocado Books Binding
            [tasks] => Array
                (
                    [0] => Finish collating the signatures
                    [1] => Fix perfect binders
                    [2] => Fold signatures
                )

        )

    [1] => Array
        (
            [job] => Avocado Books Binding
            [tasks] => Array
                (
                    [0] => Finish collating the signatures
                    [1] => Fix perfect binders
                    [2] => Fold signatures
                )

        )

)
4

2 回答 2

1

如果禁用 PDO 的准备好的语句模拟,那么重复执行此类(服务器端准备好的)语句将比多个未准备好的语句更有效:

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);

$insert_job = $dbh->prepare('
  INSERT INTO Jobs (job_title) VALUES (?)
');

$insert_task = $dbh->prepare('
  INSERT INTO Tasks (task_description, job_id) VALUES (:desc, :id)
');

$insert_task->bindParam(':desc', $task  , PDO::PARAM_STR);
$insert_task->bindParam(':id',   $job_id, PDO::PARAM_INT);

foreach (json_decode($json, TRUE) as $job) {
  $insert_job->execute([$job['job']]);
  $job_id = $insert_job->lastInsertId();
  foreach ($job['tasks'] as $task) $insert_task->execute();
}
于 2013-01-18T00:54:57.313 回答
0

试试这个:

SELECT j.job_id, GROUP_CONCAT(t.task_description) task 
FROM jobs j 
INNER JOIN tasks ON j.job_id = t.job_id 
GROUP BY j.job_id;
于 2013-01-17T18:51:13.667 回答