且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MYSQL 将多个子查询的结果除以多行

更新时间:2023-08-20 12:04:22

这是您可以通过以下查询完成整个事情的一种方法:

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;

注意:

如果您希望结果四舍五入到小数点后 2 位,请使用以下内容作为查询的第一行:

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

此处演示

注意:您没有在查询中使用任何 ORDER BY.您可能会出现随机行为.

Caution: You haven't used any ORDER BY in your query. You might get random behavior.