Row_number和并集

时间:2019-02-09 15:16:34

标签: mysql

我正在编写一个有关hackerrank挑战的查询,现在我的查询如下:

 public function user(){
    return $this->belongsToMany(User::class, 'loans')->withPivot(['loan_date','status'])->withTimeStamps();
}

但是当我执行它时,我得到以下信息:

(SELECT q1.city,q1.charsize (
    SELECT 
        city
        , MIN(LENGTH(city)) as charsize
        , ROW_NUMBER() OVER (PARTITION BY charsize,city order by city) as rowno
    from station
   ) q1 
WHERE q1.rowno = 1)
UNION
(SELECT q2.city,q2.charsize (
    SELECT 
        city
        , MAX(LENGTH(city)) as charsize
        , ROW_NUMBER() OVER (PARTITION BY charsize,city order by city) as rowno
    from station
   ) q2 
WHERE q2.rowno = 1);

这意味着我在做一些错误的语法,在sql方面我几乎没有经验,我已经看过文档,但是我一直在努力理解原因。

如果可以使用,则为表结构:

Table structure

1 个答案:

答案 0 :(得分:1)

似乎您忘记了几个FROM关键字。
而且我认为您应该使用UNION ALL而不是UNION

(SELECT q1.city,q1.charsize FROM (
    SELECT 
        city
        , MIN(LENGTH(city)) as charsize
        , ROW_NUMBER() OVER (PARTITION BY charsize,city order by city) as rowno
    from station
   ) q1 
WHERE q1.rowno = 1)
UNION ALL
(SELECT q2.city,q2.charsize FROM (
    SELECT 
        city
        , MAX(LENGTH(city)) as charsize
        , ROW_NUMBER() OVER (PARTITION BY charsize,city order by city) as rowno
    from station
   ) q2 
WHERE q2.rowno = 1);

假设您使用的是MySQL 8.0+,此查询应该可以正常工作