考虑此表table1
User_ID Field Value
1 balance 232
1 last_active 1525690435
2 balance 345
2 last_active 1525690430
要获得用户余额的总和,给定他们的last_active是> X,我可以使用子查询,如
SELECT SUM(Value) FROM table1 WHERE Field = 'balance' AND User_ID IN (
SELECT User_ID FROM table1 WHERE Field = 'last_active' AND Value > X
)
有没有更好的方法来获得相同的结果?
答案 0 :(得分:2)
答案 1 :(得分:1)
您可以编写查询,使其在语法和逻辑上正确(基于您的示例数据):
SELECT SUM(Value)
FROM table1
WHERE field = 'balance' AND
User_ID IN (SELECT USER_ID
FROM table1
WHERE field = 'last_active' AND value > X
);
为了提高效果,我建议EXISTS
和table1(USER_ID, field, value)
上的索引:
SELECT SUM(t1.Value)
FROM table1 t1
WHERE t1.field = 'balance' AND
EXISTS (SELECT 1
FROM table1 tt1
WHERE tt1.USER_ID = t1.USER_ID AND
tt1.field = 'last_active' AND tt1.value > X
);
答案 2 :(得分:0)
是的,您可以使用exists
代替
SELECT SUM(Value) Value
FROM table1 t
WHERE Field = 'balance' AND
EXISTS (SELECT 1
FROM table1
WHERE User_ID = t.User_ID AND
Field = ' last_active' AND value > X);
答案 3 :(得分:0)
尝试:如果您正在使用单一表格
SELECT SUM(Value) FROM table1 WHERE field = 'balance' AND last_active > X
通过查看查询中的User_ID
和ID
,您似乎使用了两个单独的表,因此您可以将查询编写为
SELECT SUM(A.Value)
FROM table1 A
INNER JOIN table2 B ON B.id = A.User_Id
AND B.last_active > 'x'
WHERE A.field = 'field = 'balance'