基于Multiple where子句的M​​ysql记录

时间:2017-07-26 15:13:44

标签: mysql

我有两个表,共同列是m_id,基于我必须选择最大date_time的客户详细信息让我们将此表称为客户:

+------+--------+-------+
| 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,基于我必须选择m_id和客户详细信息,如果cus_id = 2,则se_id = 12表示首先将其传递给第一个表并获取m_id和将m_id传递给第二个表,其中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)

请指导我得到正确的结果,我认为左加入会帮助我,但无法得到它

1 个答案:

答案 0 :(得分: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;