这是我的sql架构:
Table 1: scan_1 Table 2: scan_2 Table 3: scan_detail
P_no work P_no work P_no work_date
1 YES 1 YES 1 2017/11/03
2 YES 2 NO 2 2017/12/31
3 NO 3 NO 3 2017/12/13
我想从scan_1和scan_2计算P_no,其中日期范围属于scan_detail。 我使用此查询来计算scan_1和scan_2中的P_no,但无法在查询中添加scan_detail。
SELECT COUNT(*) AS pick FROM (SELECT P_no, work FROM scan_1 WHERE work = 'YES' UNION SELECT P_no, work FROM scan_2 WHERE work = 'YES') AS total
在上面的查询中,我想从scan_detail添加日期范围,如
select count(P_no) from scan_detail where work_date >='2017/11/03' and work_date <= '2017/12/31'
答案 0 :(得分:1)
您可以使用您的联合结果集扫描1&amp; 2
SELECT
COUNT(*) AS pick
FROM scan_detail d
JOIN (SELECT P_no,`work` FROM scan_1 WHERE `work` = 'YES'
UNION
SELECT P_no,`work` FROM scan_2 WHERE `work` = 'YES'
) AS s USING(P_no)
WHERE d.work_date >='2017/11/03' AND d.work_date <= '2017/12/31'
答案 1 :(得分:0)
使用连接查询添加日期时间,然后应用过滤器。伪查询在下面给出
SELECT COUNT(P_no) AS pick
FROM (SELECT a.P_no as P_no, a.work as work, b.work_date work_date
FROM scan_1
LEFT JOIN scan_details b on (a.P_no = b.P_no)
WHERE work = 'YES'
UNION
SELECT c.P_no, c.work, d.work_date work_date
FROM scan_2 c
LEFT JOIN scan_details d on (c.P_no = d.P_no)
WHERE work = 'YES'
where work_date between date1 and date2)