MySQL分组依据和不确定的结果

时间:2018-11-12 08:17:58

标签: mysql

我一直在研究正确使用MySQL Group By和Joins以避免其他列中未聚合值的不确定值。现在,通过下面的查询,在按客户ID分组时,如何确保以最少的试驾时间选择正确的Vin号码?基本上,如何确保整个行都与最短的测试行驶时间相关?

  SELECT t1.ID AS CUSTOMERID, t1.carhash, 
             MIN(t1.testdrivetime) AS testdrivetime,
               t2.vinnumber AS vinnumber

               FROM TABLE1 t1

        INNER JOIN TABLE2 t2 ON t2.vinnumber = t1.carhash

INNER JOIN (SELECT t1.ID, MIN(testdrivetime) AS testdrivetime
        FROM TABLE1
        GROUP BY t1.ID) f
    ON f.ID = t1.ID AND f.testdrivetime = t1.testdrivetime

GROUP BY ID

数据库中的时间:

|---------------------|------------------|-------------------------|
|          ID         |      carhash     |       testdrivetime     |
|---------------------|------------------|-------------------------|
|          12         |         345      |           2:22          |
|---------------------|------------------|-------------------------|
|          12         |         277      |           4:51          |
|---------------------|------------------|-------------------------|

具有上述查询的输出(错误的汽车哈希值,因为不确定):

|---------------------|------------------|-------------------------|
|          ID         |      carhash     |       testdrivetime     |
|---------------------|------------------|-------------------------|
|          12         |         277      |           2:22          |
|---------------------|------------------|-------------------------|

我想要的输出:(在同一行中具有正确的哈希值,作为最小测试行驶时间)

|---------------------|------------------|-------------------------|
|          ID         |      carhash     |       testdrivetime     |
|---------------------|------------------|-------------------------|
|          12         |         345      |           2:22          |
|---------------------|------------------|-------------------------|

1 个答案:

答案 0 :(得分:0)

  • 在子选择查询(Derived Table)中,确定每个testdrivetime的最小ID值。
  • 使用IDtestdrivetime将结果集返回到主表,以获取与最小testdrivetime值相对应的行。

尝试:

SELECT 
  t.* 
FROM your_table AS t 
JOIN 
(
  SELECT 
    ID, 
    MIN(testdrivetime) AS min_testdrivetime 
  FROM your_table 
  GROUP BY ID
) AS dt 
  ON dt.ID = t.ID AND 
     dt.min_testdrivetime = t.testdrivetime