根据其他行的数量选择行

时间:2018-02-15 23:05:22

标签: mysql

考虑这个问题:

SELECT b.biblionumber, b.title, 
    COUNT(DISTINCT i.itemnumber) AS 'Total Copies', 
    COUNT(o.itemnumber) AS 'Total Issues', 
    COUNT(DISTINCT  i.itemnumber) / COUNT(o.itemnumber) AS 'Ratio'
FROM biblio b
    LEFT JOIN items i
        ON b.biblionumber = i.biblionumber
    LEFT JOIN old_issues o
        ON o.itemnumber = i.itemnumber
            AND o.issuedate BETWEEN '2018-02-01' AND '2018-02-03'
GROUP BY b.biblionumber, b.title

如何仅显示比率>的行? 1?

我尝试过使用本地变量并添加:

WHERE @ratio > 1

但这只会杀死我的服务器(永远运行直到它崩溃)。

1 个答案:

答案 0 :(得分:0)

性能问题通常可能是由于连接后聚合造成的,因为连接会产生一个非常大的中间表。在加入之前对表进行分组可能会更好。

SELECT b.biblionumber, b.title, 
    SUM(i.count) AS `Total Copies`, SUM(o.count) AS `Total Issues`, 
    SUM(i.count)/SUM(o.count) AS Ratio
FROM biblio AS b
INNER JOIN (
    SELECT biblionumber, itemnumber, COUNT(*) AS count
    FROM items
    GROUP BY biblionumber, itemnumber) AS i ON b.biblionumber = i.biblionumber
INNER JOIN (
    SELECT itemnumber, COUNT(*) AS count
    FROM old_issues
    GROUP BY itemnumber) AS o ON i.itemnumber = o.itemnumber
GROUP BY b.biblionumber, b.title
HAVING Ratio > 1

我也将其从LEFT JOIN更改为INNER JOIN。为了获得正比率,您需要在两个表中匹配,因此不需要允许具有外部联接的不匹配行。内连接往往在MySQL中表现更好,因此在可能的情况下总是更喜欢它们。

您也可以通过切换到INNER JOIN来解决原始问题。