2012-09-24 20 views
0

我有一个名为'data'的表,它存储了用户的电子邮件地址和城市,我想查找最受欢迎的电子邮件域。我使用以下查询来查找具有最大值的行。 exapmple我的表:substring_index函数不存在错误

Email   Name  City 
[email protected]  John California 
[email protected]  Leo sydney 
[email protected]  Ross NY 
[email protected]  Ronny Canberra 
[email protected]  Monty London 
[email protected]  Jim washington 
[email protected]  Finn Las vegas 

我一直在使用这个查询

select x.city, x.No_of_People from (select e.city, count(e.city) as No_of_People from data e group by e.city) x 
where x.No_of_People = (select max(x2.No_of_People) from (select e2.city, count(e2.city) as No_of_People from data e2 group by   e2.city) x2) 

计算的答案,但我不wan't使用的限制,因为它没有返回多行。所以我用用这个answer

select 
    x.substring_index (email,'@',-1), 
    x.No_of_Users 
from 
    (select 
    e.substring_index (email,'@',-1), 
    count(e.substring_index (email,'@',-1)) as No_of_Users 
    from 
    data e 
    group by 
    e.substring_index (email,'@',-1)) x 
where 
    x.No_of_Users = 
    (select 
     max(x2.No_of_Users) 
    from 
     (select 
     e2.substring_index (email,'@',-1), 
     count(e2.substring_index (email,'@',-1)) as No_of_Users 
     from 
     data e2 
     group by 
     e2.substring_index (email,'@',-1)) x2) 

,我使用正在给这个错误“功能e2.substring_index不存在”查询以下查询。帮我。

回答

3

您的语法在使用该函数时是错误的。别名在列上,而不是函数。举例来说,你最后的子查询应该使用这个语法:

from (select substring_index(e2.email,'@',-1) as strind, 
       count(substring_index(e2.email,'@',-1)) as No_of_Users 
     from data e2 
     group by substring_index (e2.email,'@',-1) 
     ) x2 

我还被评为第一列,那么你可以参考它,如果你想要的子查询之外。

要计算出现的次数在一个字符串,用这一招:

(length(e2.email) - length(replace(e2.email, '@', '')) as numAmpersands 
+0

是男人。你是对的。我的语法完全不合逻辑。谢谢,你节省了我的时间。 – Alonso

+0

嘿,请告诉一件事。我纠正了语法,并给出了正确的答案。我的意思是它显示了正确的电子邮件域数量。但第二行代码不起作用。 select substring_index(x.email,'@', - 1), x.No_of_Users from ............... 错误是“Unknown column'x.email'在'字段列表' 如果我删除这一行,'substring_index(x.email,'@', - 1)',那么它的作品。但我也需要显示域名。 – Alonso

+0

上述语句'substring_index(x.email,'@', - 1)'是否有错误?我如何显示名称?????? – Alonso