2017-07-26 64 views
1

我有在共同列兩個表是M_ID基礎上,我必須選擇客戶詳細最大DATE_TIME讓我們把該表作爲客戶:Mysql的記錄基於多個where子句

+------+--------+-------+ 
| m_id | cus_id | se_id | 
+------+--------+-------+ 
| 5 | 2  | 12 | 
| 7 | 2  | 12 | 
| 9 | 3  | 13 | 
| 8 | 2  | 12 | 
+------+--------+-------+ 

這是表cus_detail:

+---------+----------+--------------------+ 
| m_id | taxonomy | date_time   | 
+---------+----------+--------------------+ 
|  5 | es  |2015-09-16 11:46:53 | 
|  5 | es1  |2015-09-16 11:47:40 | 
|  7 | es2  |2015-09-16 11:49:46 | 
|  7 | es2  |2015-09-16 12:20:31 | 
|  8 | es3  |2015-09-23 07:01:21 | 
|  8 | es3  |2015-09-23 07:02:21 | 
|  9 | es4  |2015-09-23 07:03:17 | 
|  4 | es5  |2015-09-23 07:50:29 | 
+---------+----------+--------------------+ 

我已經從客戶的兩個輸入被cus_id和SE_ID基於我必須選擇具有最大DATE_TIME值M_ID和客戶細節如果cus_id = 2和SE_ID = 12意味着第一它傳遞給第一個表,並獲得m_id並將該m_id傳遞給第二個表wh ERE DATE_TIME也最大我期待下面的結果

+---------+----------+--------------------+ 
| m_id | taxonomy | date_time   | 
+---------+----------+--------------------+ 
|  5 | es1  |2015-09-16 11:47:40 | 
|  7 | es2  |2015-09-16 12:20:31 | 
|  8 | es3  |2015-09-23 07:02:21 | 
+---------+----------+--------------------+ 

我正在嘗試下面的MySQL查詢,但沒有得到它的答案

SELECT * FROM `cus_detail` WHERE m_id in (SELECT m_id from customer where cus_id=2 and se_id=12) and date_time=(select max(date_time) from cus_detail) 

請指導我得到正確的結果,我想離開加盟意願幫我,但無法得到它

+0

編寫你想要的答案,並且得到你嘗試過什麼 –

+0

我沒有得到任何輸出答案,我提到了預期的結果 – Sathish

回答

1

您所查詢的是:

SELECT * FROM `cus_detail` 
WHERE m_id in (SELECT m_id from customer where cus_id=2 and se_id=12) 
and date_time=(select max(date_time) from cus_detail) 

date_time選擇缺少一個關鍵m_id來確定正確的max(date_time)

SELECT * FROM cus_detail cd 
INNER JOIN customer c ON c.m_id=cd.m_id AND c.cus_id=2 and c.se_id=12 
INNER JOIN (select max(date_time) date_time,m_id from cus_detail GROUP BY m_id) cd2 
ON cd.m_id=cd2.m_id and cd.date_time=cd2.date_time;