2013-08-20 78 views
0

我有兩個查詢其返回的結果如下(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)與NULL值填充在SELECT語句,但由此產生不穩定的結果。

+----------------+---------+-------------+---------------------+ 
| 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

試試這個

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 
+0

這很酷,非常感謝。 – cookie