两个查询都使用相同的表(此处为:test)
首先查询:
SELECT `test` as t1, COUNT( * ) as t2
FROM `test_table`
WHERE `test` > 5
GROUP BY `test`
以表格
返回结果--------------------------------------------------
| t1 | t2 |
--------------------------------------------------
| 6 | 2 |
--------------------------------------------------
| 8 | 7 |
--------------------------------------------------
第二次查询:
SELECT TRUNCATE(((num1/num2) * 100),3) as t3
FROM
(SELECT COUNT( * ) as num1
FROM `test_table`
WHERE test > 5
group by `test`) a,
(SELECT COUNT( * ) as num2
FROM `test_table`
WHERE test > 5) b
以表格
返回结果--------------------------------------------------
| t3 |
--------------------------------------------------
| 40.456% |
--------------------------------------------------
| 59.544% |
--------------------------------------------------
我想要的是:
--------------------------------------------------
| t1 | t2 | t3 |
--------------------------------------------------
| 6 | 2 | 40.456% |
--------------------------------------------------
| 8 | 7 | 59.544% |
--------------------------------------------------
我该怎么办?联盟将t3结果置于t1 t2以下,或许加入声明?但加入什么?或者我可以从这两个选择所有数据的一个查询?
答案 0 :(得分:1)
在select中使用子查询使其非常易读
DROP TABLE IF EXISTS TEST_TABLE;
CREATE TABLE TEST_TABLE(TEST INT);
INSERT INTO TEST_TABLE VALUES
(6),(6),
(8),(8),(8),(8),(8),(8),(8);
SELECT `test` as t1, COUNT(*) as t2,
TRUNCATE(COUNT(*) / (SELECT COUNT(*) FROM TEST_TABLE WHERE TEST > 5) * 100,3) AS T3
FROM `test_table`
WHERE `test` > 5
GROUP BY `test`
结果
+------+----+--------+
| t1 | t2 | T3 |
+------+----+--------+
| 6 | 2 | 22.222 |
| 8 | 7 | 77.777 |
+------+----+--------+
2 rows in set (0.00 sec)
答案 1 :(得分:0)
SELECT
Z.t1, Z.t2, Z1.t3
FROM
(SELECT
`test` AS t1, COUNT(*) AS t2
FROM
`test_table`
WHERE
`test` > 5
GROUP BY `test`) Z
INNER JOIN
(SELECT
t1, TRUNCATE(((num1 / num2) * 100), 3) AS t3
FROM
(SELECT
test t1, COUNT(*) AS num1
FROM
`test_table`
WHERE
test > 5
GROUP BY `test`) a, (SELECT
COUNT(*) AS num2
FROM
`test_table`
WHERE
test > 5) b) Z1 ON Z.t1 = Z1.t1;
尝试以上代码。
希望这会对你有所帮助。
答案 2 :(得分:0)
这可以通过对第二个查询进行一些修改来完成:
SELECT a.t1, num1 as t2, TRUNCATE(((num1/num2) * 100),3) as t3
FROM
(SELECT `test` as t1, COUNT( * ) as num1
FROM `test_table`
WHERE test > 5
group by `test`) a,
(SELECT COUNT( * ) as num2
FROM `test_table`
WHERE test > 5) b
答案 3 :(得分:0)
在您的示例中构建它的方式您应该能够在test_table.test(您正在使用Group By的字段)上加入它们