我有两个查询,第一个生成像
这样的表SELECT COUNT(channel) AS messages FROM Chats WHERE message LIKE '%word%' GROUP BY UNIX_TIMESTAMP(time) DIV 3600
+-----+
| 123 |
| 127 |
| 332 |
| 219 |
+-----+
和第二个
SELECT COUNT(channel) AS messages FROM Chats GROUP BY UNIX_TIMESTAMP(time) DIV 3600
+-----+
| 222 |
| 579 |
| 590 |
| 377 |
+-----+
现在我想将第一个表中的所有结果除以第二个表中的相应值(结果四舍五入,必须手动计算):
+------+
| 0.55 | #123/222
| 0.46 | #127/279
| 0.56 | #332/590
| 0.58 | #219/377
+------+
答案 0 :(得分:2)
以下是通过以下查询完成整个事情的一种方法:
SELECT
(dividendTable.messages / divisorTable.messages) AS result
FROM
(
SELECT
firstTable.messages,
@rn1 := @rn1 + 1 AS row_number
FROM
(
SELECT
COUNT(channel) AS messages
FROM Chats
WHERE message LIKE '%word%'
GROUP BY UNIX_TIMESTAMP(time) DIV 3600
) FirstTable, (SELECT @rn1 := 0) var1
) AS dividendTable
INNER JOIN
(
SELECT
secondTable.messages,
@rn2 := @rn2 + 1 AS row_number
FROM
(
SELECT
COUNT(channel) AS messages
FROM Chats
GROUP BY UNIX_TIMESTAMP(time) DIV 3600
) secondTable, (SELECT @rn2 := 0) var2
) AS divisorTable
ON dividendTable.row_number = divisorTable.row_number;
注意:强>
如果您想将结果四舍五入到小数点后的2位数,请使用以下作为查询的第一行:
SELECT
ROUND((dividendTable.messages / divisorTable.messages),2) AS result
警告:您尚未在查询中使用任何ORDER BY。你可能会得到随机行为。