可以在一个查询中执行双重选择语句,并使用sum
和suma
分别显示每个值,以便第一个选择我只期望一个值,并且对于第二个4值。
echo ' ' . htmlentities($rowsm['sum'], ENT_QUOTES, 'UTF-8') . '<br>';
$query = "SELECT SUM(a.totalpoints) as sum
FROM total as a
WHERE a.id = '$id'
GROUP BY a.id
UNION ALL
SELECT SUM(s.points) as suma
FROM points as s
GROUP BY s.id
这是我得到的输出
A 21 first select
A 11 second select
A 10 second select
A 9 second select
A 14 second select
21总和
A 11 points
A 10 points
A 9 points
A 14 points
答案 0 :(得分:1)
在UNION ALL中,相应的字段需要具有相同的名称,否则系统将如何决定在列标题中显示哪个名称?您的SQL必须采用以下形式:
SELECT SUM(a.totalpoints) as suma
FROM total as a
WHERE a.id = '$id'
GROUP BY a.id
UNION ALL
SELECT SUM(s.points) as suma
FROM points as s
GROUP BY s.id
此外,sum是一个关键字,因此您不能使用名为sum的别名。即“作为总和”可能无效。
答案 1 :(得分:0)
除非是一个事务,否则不能在一个查询中调用多个select语句。 将您的查询更改为:
$query = "
START TRANSACTION;
SELECT SUM(a.totalpoints) as suma
FROM total as a
WHERE a.id = '$id'
GROUP BY a.id
UNION ALL
SELECT SUM(s.points) as suma
FROM points as s
GROUP BY s.id
COMMIT;";
同样@Swagata提到你不能使用关键字作为别名