我想在SELECT中使用SELECT来获取一些值(我已经完成了这个) 问题是,我想在mysql中显示这些数据,总和,这就是问题所在。
我不会发布原始代码,但请查看此示例。
SELECT id, (SELECT COUNT(x) FROM xyz where id=usr.id) as value_1,
(SELECT COUNT(y) FROM zyx where id=usr.id) as value_2
FROM users AS usr
这是正确的,但我想将value_1和value_2相加。
当我这样做时
SELECT id,
(SELECT COUNT(x) FROM xyz where id=usr.id) as value_1,
(SELECT COUNT(y) FROM zyx where id=usr.id) as value_2,
(value_1+value_2) as my_sum_value
FROM users AS usr
我收到有关“value_1”和“value_2”未找到的信息。
我发现,我可以使用
SELECT id,
(SELECT COUNT(x) FROM xyz where id=usr.id) as value_1,
(SELECT COUNT(y) FROM zyx where id=usr.id) as value_2,
((SELECT COUNT(x) FROM xyz where id=usr.id) as value_1,
(SELECT COUNT(y) FROM zyx where id=usr.id)+
(SELECT COUNT(y) FROM zyx where id=usr.id) as value_2) as my_sum_value
FROM users AS usr
但是,我必须写“两次”我的所有代码。 为什么我不能使用名为“value_1”和“value_2”的“别名”? 查询后,这个值是否正确,如何访问总和值?
答案 0 :(得分:1)
试试这个
SELECT id,
SUM(
(SELECT COUNT(x) FROM xyz where id=usr.id),
(SELECT COUNT(y) FROM zyx where id=usr.id)
) as my_sum_value
FROM users AS usr
你不能使用变量,因为它们在子查询中......