SQL查询正确性

时间:2017-03-04 03:37:35

标签: mysql sql-server

我正在努力寻找与不同客户进行过大多数旅行的//### get table drawn function fetchTable(t){ console.log('enter fetchTable fn, table: '+t); $.getJSON( "tabelmgr_ajax.pl?fetchTable="+t, function( data ) { var dataSet = []; $.each( data, function( key, val ) { dataSet.push(val); }); console.log('dataSet='+dataSet); oTable = $('#'+t).DataTable({ data: dataSet, bJQueryUI: true, sDom: '<"H"ilpt>', // '<"H"lip>t<>' or '<"H"lip>t' "dom": '<"top"iflp>', //show evrythin on top bar }); oTable.draw().columns().every( function () { var that = this; $( 'input', this.footer() ).on( 'keyup change', function () { if ( that.search() !== this.value ) { that.search( this.value ).draw(); } }); }); }); }; 。我不想要一个完整的解决方案,因为我知道如何做到这一点。但是当我运行查询时,我收到错误:

carid

我的SQL查询是:

Table 'test.v' doesn't exist
1 statement failed.

当我选择SELECT * FROM ( ( SELECT carid, COUNT(DISTINCT cusid) AS counter FROM trips GROUP BY carid ) v ) WHERE v.counter = ( SELECT MAX(counter) FROM v ) 时,我得到了正确的结果。谁能解释一下我发生了什么?

1 个答案:

答案 0 :(得分:1)

在MySQL中,你不能直接使用这样的别名。您需要再次重写子查询。

试试这个:

select *
from (
    select carid, count(distinct cusid) as counter
    from trips
    group by carid
    ) v
where v.counter = (
        select max(counter)
        from (
            select count(distinct cusid) as counter
            from trips
            group by carid
            ) t
        )

目前尚不清楚您使用的是哪个DBMS。如果您使用的是SQL Server,则可以使用CTE:

with v
as (
    select carid, count(distinct cusid) as counter
    from trips
    group by carid
    )
select *
from v
where counter = (
        select max(counter)
        from v
        )