SQL加入三个表

时间:2013-12-09 13:30:29

标签: mysql sql

加入三个SQL表时遇到问题。简单地认为有3个表叫A,B和C.表A包含有关出勤率,日期等出勤率的数据。其他两个表包含每个班次的数据,例如时间,时间。特定班次的数据只能包含在一个表格中。

表A

shift_id  |    date
--------------------
  001     | 2013-12-01  
  002     | 2013-12-01  
  003     | 2013-12-01  

表B

shift_id  | in_time | out_time
------------------------------
  001     | 07:10   | 04:10
  003     | 07:30   | 05:10

表C //不包含out_time列

shift_id  | in_time 
--------------------
  002     | 07:45   

预期输出

shift_id  | in_time | out_time
------------------------------
  001     | 07:10   | 04:10
  002     | 07:45   | 00:00
  003     | 07:30   | 05:10

Plz帮帮我。

4 个答案:

答案 0 :(得分:2)

我认为UNION可以帮到你。

SELECT 'FROM A', A.shift_id, B.in_time, B.out_time
FROM A INNER JOIN B ON A.shift_id = B.shift_id

UNION ALL

SELECT 'FROM B', A.shift_id, C.in_time, '00:00'
FROM A INNER JOIN C ON A.shift_id = C.shift_id

答案 1 :(得分:1)

假设shift_id是表B和C的外键,即你不需要验证表A中是否存在shift_id

SELECT 
    shift_id, in_time, out_time 
FROM 
    B
UNION  
SELECT 
    shift_id, in_time,'00:00' as out_time 
FROM 
    C

否则

SELECT 
    shift_id, in_time, out_time 
FROM 
    B WHERE shift_id IN (SELECT shift_id from A)
UNION  
SELECT 
    shift_id, in_time,'00:00' as out_time 
FROM 
    C WHERE shift_id IN (SELECT shift_id from A);

如果您需要验证表A中是否存在shift_id

答案 2 :(得分:1)

您可以使用IFNULL()(参考:http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html):

SELECT A.shift_id, IFNULL(B.in_time,C.in_time), IFNULL(B.out_time, '00:00') 
FROM A 
LEFT JOIN B ON A.shift_id = B.shift_id 
LEFT JOIN C ON A.shift_id = C.shift_id;

答案 3 :(得分:0)

SELECT a.shift_id
     , a.date
     , x.in_time
     , COALESCE(x.out_time,'00:00:00') out_time 
  FROM table_a a 
  JOIN 
     ( SELECT shift_id,in_time,out_time FROM table_b 
       UNION 
       SELECT shift_id,in_time,NULL FROM table_c
     ) x 
    ON x.shift_id = a.shift_id
 ORDER
    BY shift_id;