我有两个查询返回以下结果(A)& (B)说:
SELECT username, ext_num FROM user u
JOIN extension e
ON u.id=e.user_id;
+----------+---------+
| username | ext_num |
+----------+---------+
| test | 2459871 |
+----------+---------+
1 row in set (0.00 sec)
SELECT TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at)) as `duration (sec)`, oc.ext_num, oc.destination, oc.created_at, oc.call_id
-> FROM on_connected oc
-> JOIN on_disconnected od ON od.call_id = oc.call_id
-> WHERE oc.ext_num = 2459871\G;
*************************** 1. row ***************************
duration (sec): 4
ext_num: 2459871
destination: 55544466677
created_at: 2013-08-19 17:11:53
call_id: 521243ad953e-965inwuz1gku
*************************** 2. row ***************************
duration (sec): 4
ext_num: 2459871
destination: 55544466677
created_at: 2013-08-20 10:28:48
call_id: 521336b51225-0w4mkelwpfui
2 rows in set (0.00 sec)
我想加入上面的两个表来返回类似的内容:
+----------------+----------------+-----------------------+---------------------+---------------------------+
| username | duration (sec) | ext_num | destination | created_at | call_id |
+----------------+----------------+-----------------------+---------------------+---------------------------+
| test | 4 | 2459871 | 55544466677 | 2013-08-19 17:11:53 | 521243ad953e-965inwuz1gku |
| test | 4 | 2459871 | 55544466677 | 2013-08-20 10:28:48 | 521336b51225-0w4mkelwpfui |
+----------------+----------------+-----------------------+---------------------+---------------------------+
理论上,如果需要,我可以在“call_id”上返回针对任何特定“ext_num”的所有电话或更精细的报告。
我尝试了什么?我最初想到的是UNION运算符:
(A) UNION (B);
其中(A)在SELECT语句中用NULL值填充,但这会产生不稳定的结果。
+----------------+---------+-------------+---------------------+
| duration (sec) | ext_num | destination | created_at |
+----------------+---------+-------------+---------------------+
| 4 | 2459871 | 55544466677 | 2013-08-19 17:11:53 |
| 4 | 2459871 | 55544466677 | 2013-08-20 10:28:48 |
| test | 2459871 | NULL | NULL |
+----------------+---------+-------------+---------------------+
3 rows in set (0.01 sec)
答案 0 :(得分:0)
试试这个
SELECT * FROM
(SELECT username, ext_num FROM USER u
JOIN extension e
ON u.id=e.user_id) a
INNER JOIN
(SELECT TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at)) AS `duration (sec)`, oc.ext_num, oc.destination, oc.created_at, oc.call_id
FROM on_connected oc
JOIN on_disconnected od ON od.call_id = oc.call_id
WHERE oc.ext_num = 2459871 ) b
ON (a.ext_num = b.ext_num)
其他方式将所有4个表连接在一起
SELECT u.username TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at)) AS `duration (sec)`, oc.ext_num, oc.destination, oc.created_at, oc.call_id
FROM on_connected oc
JOIN on_disconnected od ON od.call_id = oc.call_id
JOIN extension e ON (oc.ext_num = e.ext_num)
JOIN `user` u ON (u.id=e.user_id)
WHERE oc.ext_num = 2459871