我有以下语法上不正确的查询,包含别名in_Degree和out_degree:
insert into userData
select user_name,
(select COUNT(*) from tweets where rt_user_name = u.USER_NAME)in_degree,
(select COUNT(*) from tweets where source_user_name = u.user_name)out_degree,
in_degree + out_degree(freq)
from users u
查询中的问题是选择列表中的第4项别名为freq。我希望第4项的值为in_degree + out_degree。蛮力非常慢的解决方案是复制并通过两个子查询并添加它们。
答案 0 :(得分:2)
您可以使用子查询:
insert into userData
select user_name,
in_degree,
out_degree,
in_degree + out_degree
from
(
select user_name,
(select COUNT(*) from tweets where rt_user_name = u.USER_NAME)in_degree,
(select COUNT(*) from tweets where source_user_name = u.user_name)out_degree
from users u
) src
或者您可以使用:
insert into userData
select user_name,
count(distinct in_t.*) in_degree,
count(distinct out_t.*) out_degree,
count(distinct in_t.*) + count(distinct out_t.*)
from users u
left join tweets in_t
on u.USER_NAME = in_t.rt_user_name
left join tweets out_t
on u.USER_NAME = out_t.source_user_name
group by u.user_name
答案 1 :(得分:2)
正如您所发现的那样,除了HAVING子句或ORDER BY子句外,您不能引用该选择列表中给出的别名。
一种选择是将您的查询用作“内联视图”,并围绕该视图编写包装器查询。
但是,如果你想让它“快速”,你可能会考虑(作为一种选择)采取完全不同的方法。您可以获取所有用户的计数,然后使用LEFT JOIN运算符,而不是使用相关子查询来获取每个单独用户的计数,例如
SELECT u.user_name
, IFNULL(i.cnt,0) AS in_degree
, IFNULL(o.cnt,0) AS out_degree
, IFNULL(i.cnt,0)+IFNULL(o.cnt,0) AS freq
FROM users u
LEFT
JOIN (SELECT rt_user_name, COUNT(*) AS cnt FROM tweets
GROUP BY rt_user_name) i
ON i.rt_user_name = u.user_name
LEFT
JOIN (SELECT source_user_name, COUNT(*) AS cnt FROM tweets
GROUP BY source_user_name) o
ON o.source_user_name = u.user_name
答案 2 :(得分:0)
这应该有效:
insert into userData
SELECT T.user_name,
T.in_degree,
T.out_degree,
(T.in_degree + T.out_degree) as freq
FROM (SELECT user_name,
(select COUNT(*) from tweets where rt_user_name = u.USER_NAME) as in_degree,
(select COUNT(*) from tweets where source_user_name = u.user_name) as out_degree
FROM users u) T
答案 3 :(得分:0)
以一种快速的方式,我会做类似的事情:
insert into userData
select
TMP.user_name,
TMP.in_degree,
TMP.out_degree,
(TMP.in_degree + TMP.out_degree) degreeSum
from(
select user_name,
(select COUNT(*) from tweets where rt_user_name = u.USER_NAME)in_degree,
(select COUNT(*) from tweets where source_user_name = u.user_name)out_degree
from users u
) TMP