简体   繁体   中英

JOINING 2 MYSQL queries

I have two queries below, the first one is query for my DataTables and the second one is for the regular HTML table.

The first query is:

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

I executed the query in my php file and DataTables works perfectly, and now the second query:

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'

The second query seems working good on regular HTML Table with GET parameters. I need to join the second query with the first query and use that query on DataTables server side processing file. I'm having problem on joining progress field from second query into first query.

Put the second query into the first one as a subquery.

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

Use INNER JOIN instea of LEFT JOIN if work_sheet_machine always has matching rows for the rows in work_order .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM