如何在mysql

时间:2018-10-16 14:09:35

标签: mysql select

我有两个表:coinscoin_history

coins

|id | symbol | date     | 
+---+--------+----------+
|1  |  BTC   |01-02-2011|
|2  |  ETH   |21-02-2011|
|3  |  XRP   |08-01-2011|
|4  |  BCH   |25-01-2011|

coin_history表;每个硬币在日期上的排名

|id | coin_id | rank   | date     | 
+---+---------+--------+----------+
| 1 |    1    |   1    |01-02-2018|
| 2 |    1    |   1    |02-02-2018|
| 3 |    1    |   1    |04-02-2018|
| 4 |    2    |   2    |01-02-2018|
| 5 |    2    |   3    |02-02-2018|
| 6 |    2    |   2    |04-02-2018|
| 7 |    3    |   3    |01-02-2018|
| 8 |    3    |   2    |02-02-2018|
| 9 |    3    |   4    |04-02-2018|
|10 |    4    |   4    |01-02-2018|
|11 |    4    |   4    |02-02-2018|
|12 |    4    |   3    |04-02-2018|

我想从coins的最新排名中抽取coin_history的每个硬币

某事链接了此结果:

|coin_id | symbol |  rank  |
+--------+--------+--------+
|   1    |  BTC   |   1    |
|   2    |  ETH   |   2    |
|   4    |  BCH   |   3    |
|   3    |  XRP   |   4    |

我尝试了一些查询,但所有查询均导致此错误

  

这与sql_mode = only_full_group_by

不兼容

3 个答案:

答案 0 :(得分:2)

  • Derived Table中,从特定硬币的历史记录中获取日期的最大值。
  • 将此结果集与您的主表相连,以仅获取与硬币的最近日期相对应的行。
  • 最终,使用ORDER BY来获得排名升序的结果。

尝试:

SELECT 
  c.coin_id, 
  c.symbol, 
  ch.rank 
FROM 
  coins AS c 
JOIN 
  coin_history AS ch 
    ON ch.coin_id = c.coin_id 
JOIN 
  (
   SELECT coin_id, 
          MAX(date) AS max_date 
   FROM coin_history 
   GROUP BY coin_id 
  ) AS dt 
    ON ch.coin_id = dt.coin_id AND 
       ch.date = dt.max_date
ORDER BY ch.rank

答案 1 :(得分:2)

MySQL还有另一种更简单的方法,但它仅是MySQL,因此当您需要代码中的数据库可移植性时不要使用此方法。

结合使用GROUP_CONCAT和嵌套的SUBSTRING_INDEX函数来获取第一个元素/项目,也可以用来获取额外的列,以保留正确的分组信息。

注意:SET SESSION group_concat_max_len = @@max_allowed_packet; SELECT coins.id AS coin_id , coins.symbol , CAST( SUBSTRING_INDEX( SUBSTRING_INDEX( GROUP_CONCAT(coin_history.rank ORDER BY coin_history.date DESC) , ',' , 1 ) , ',' , -1 ) AS UNSIGNED) AS rank FROM coins INNER JOIN coin_history ON coins.id = coin_history.coin_id GROUP BY coins.id , coins.symbol ORDER BY rank 对于使用非常重要,否则GROUP_CONCAT将仅显示1024字节。

查询

| coin_id | symbol | rank |
| ------- | ------ | ---- |
| 1       | BTC    | 1    |
| 2       | ETH    | 2    |
| 4       | BCH    | 3    |
| 3       | XRP    | 4    |

结果

allprojects {
    repositories {
        jcenter()
        mavenLocal()
        mavenCentral()
        google()
    }
}

DB Fiddle demo

答案 2 :(得分:0)

SELECT q.*from
  (SELECT h.*, c.symbol
   FROM `coin_history` AS h
   JOIN coins AS c ON h.coin_id = c.id
   ORDER BY h.date DESC
   LIMIT 50) AS q
GROUP BY q.coin_id
ORDER BY q.rank ASC