加入2个MYSQL查询

时间:2017-02-12 17:30:04

标签: php mysql datatables

我在下面有两个查询,第一个是查询我的 DataTables ,第二个查询是常规HTML表格。

第一个查询是:

SELECT a.*, b.personnel_name 
FROM `work_order` as a 
LEFT JOIN `personnel_master_data` as b ON a.`reg_no` = b.`reg_no` 
WHERE a.`status` = 'Continue' 
GROUP BY `id` 
$sOrder 
$sLimit

我在我的php文件中执行了查询,DataTables完美运行,现在是第二个查询:

SELECT d.`wo_number`, SUM(d.`crew_est` * d.`manhour_est`) AS 'crew_kali_manhours', 
    CONCAT(((SUM(d.`crew_est` * d.`manhour_est`) / 
            (SELECT SUM(c.`crew_est` * c.`manhour_est`) 
             FROM `work_sheet_machine` AS c 
             WHERE c.`wo_number` = '$wo_number')) * 100)) AS `progress` 
FROM `work_sheet_machine` AS d 
WHERE d.`status` = 'FINISH' AND d.`wo_number` = '$wo_number'

第二个查询似乎在使用GET参数的常规HTML表上运行良好。我需要使用第一个查询加入第二个查询,并在 DataTables 服务器端处理文件上使用该查询。我在将progress字段从第二个查询加入第一个查询时遇到问题。

1 个答案:

答案 0 :(得分:0)

将第二个查询作为子查询放入第一个查询中。

SELECT a.*, b.personnel_name, e.crew_cali_manhours, e.progress
FROM `work_order` as a 
LEFT JOIN `personnel_master_data` as b ON a.`reg_no` = b.`reg_no`
LEFT JOIN (
    SELECT d.`wo_number`, SUM(d.`crew_est` * d.`manhour_est`) AS 'crew_kali_manhours', 
        CONCAT(((SUM(d.`crew_est` * d.`manhour_est`) / 
                (SELECT SUM(c.`crew_est` * c.`manhour_est`) 
                 FROM `work_sheet_machine` AS c 
                 WHERE c.`wo_number` = d.wo_number)) * 100)) AS `progress` 
    FROM `work_sheet_machine` AS d 
    WHERE d.`status` = 'FINISH'
    GROUP BY wo_number
) AS e ON e.wo_number = a.wo_number
WHERE a.`status` = 'Continue' 
GROUP BY `id` 
$sOrder 
$sLimit

如果INNER JOIN LEFT JOIN的行总是匹配work_sheet_machine中的行,请使用work_order的{​​{1}}字符。