问题
I have two queries, the first one generating a table like
SELECT COUNT(channel) AS messages FROM Chats WHERE message LIKE '%word%' GROUP BY UNIX_TIMESTAMP(time) DIV 3600
+-----+
| 123 |
| 127 |
| 332 |
| 219 |
+-----+
and the second one
SELECT COUNT(channel) AS messages FROM Chats GROUP BY UNIX_TIMESTAMP(time) DIV 3600
+-----+
| 222 |
| 579 |
| 590 |
| 377 |
+-----+
Now I would like to divide all results from the first table by the corresponding value in the second one (results rounded, had to calculate it manually):
+------+
| 0.55 | #123/222
| 0.46 | #127/279
| 0.56 | #332/590
| 0.58 | #219/377
+------+
回答1:
Here's one way you can accomplish the whole thing by the following query:
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;
Note:
If you want the result rounded up to 2 digits after the decimal point then use the following as the first line of the query:
SELECT
ROUND((dividendTable.messages / divisorTable.messages),2) AS result
Demo Here
Caution: You haven't used any ORDER BY in your query. You might get random behavior.
来源:https://stackoverflow.com/questions/36233810/mysql-divide-results-from-multiple-subqueries-with-multiple-rows