Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql SQL查询正确性_Mysql_Sql Server - Fatal编程技术网

Mysql SQL查询正确性

Mysql SQL查询正确性,mysql,sql-server,Mysql,Sql Server,我正在努力寻找与不同客户进行了最多旅行的carid。我不想要一个完整的解决方案,因为我知道怎么做。但是当我运行查询时,我得到了错误: Table 'test.v' doesn't exist 1 statement failed. 我的SQL查询是: SELECT * FROM ( ( SELECT carid, COUNT(DISTINCT cusid) AS counter FROM trips GROUP BY carid

我正在努力寻找与不同客户进行了最多旅行的
carid
。我不想要一个完整的解决方案,因为我知道怎么做。但是当我运行查询时,我得到了错误:

Table 'test.v' doesn't exist
1 statement failed.
我的SQL查询是:

SELECT * FROM (
    (
        SELECT carid, COUNT(DISTINCT cusid) AS counter
        FROM trips
        GROUP BY carid
    ) v
)
WHERE v.counter = (
        SELECT MAX(counter)
        FROM v
)

当我选择
v.counter=2
时,我得到了正确的结果。有人能解释一下发生了什么吗?

在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
        )

MySQL还是SQL Server?如果您的问题是关于MS SQL Server的,您可以使用或来实现这一点。使用MySQL,可能是最好的选择。为什么?在执行from语句时,v不是被创建为一个临时表吗?在此之后,where子句可以引用v table吗?@Varun-是的,创建了临时表,但它不可用于这样的查询。它已经被查询过了。如果您使用的是SQL server(在答案中添加了一个示例),那么一个选项是使用CTE(公共表表达式)。