5

我有一个如下所示的查询

SELECT
venueid as VENUES, venue2.venue AS LOCATION,
(SELECT COUNT(*) FROM events WHERE (VENUES = venueid) AND eventdate < CURDATE()) AS number
FROM events
    INNER JOIN venues as venue2 ON events.venueid=venue2.id
GROUP BY VENUES
ORDER BY number DESC

我想限制计数以计算表中的最后 5 行(按 id 排序)但是当我添加 limt 0,5 时,结果似乎没有改变。在计算时,您在哪里添加限制以限制正在计算的行数?

    CREATE TABLE venues (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        venue VARCHAR(255)
    ) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;

    CREATE TABLE categories (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        category VARCHAR(255)
    ) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;

    CREATE TABLE events (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        eventdate DATE NOT NULL,
        title VARCHAR(255),
        venueid INT,
        categoryid INT
    ) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;

    INSERT INTO venues (id, venue) VALUES
    (1, 'USA'),
    (2, 'UK'),
    (3, 'Japan');

    INSERT INTO categories (id, category) VALUES
    (1, 'Jazz'),
    (2, 'Rock'),
    (3, 'Pop');

    INSERT INTO events (id, eventdate, title, venueid, categoryid) VALUES
    (1,20121003,'Title number 1',1,3),
    (2,20121010,'Title number 2',2,1),
    (3,20121015,'Title number 3',3,2),
    (4,20121020,'Title number 4',1,3),
    (5,20121022,'Title number 5',2,1),
    (6,20121025,'Title number 6',3,2),
    (7,20121030,'Title number 7',1,3),
    (8,20121130,'Title number 8',1,1),
    (9,20121230,'Title number 9',1,2),
    (10,20130130,'Title number 10',1,3);

预期结果应如下所示

    |VENUES |LOCATION   |NUMBER |
    |1      |   USA     |   3   |
    |2      |   UK      |   1   |
    |3      |   Japan   |   1   |

截至发布 id 9,8,7,6,5 是当前日期之前的最后 5 个事件。

有关完整表格的详细信息,请参阅下面的 SQL Fiddle 链接。

http://sqlfiddle.com/#!2/21ad85/32

4

1 回答 1

4

此查询为您提供了您尝试分组和计数的五行:

SELECT *
FROM events
WHERE eventdate < CURDATE()
ORDER BY eventdate DESC
LIMIT 5

现在您可以将此查询用作子查询。您可以加入子查询的结果,就像它是一个普通的表一样:

SELECT
    venueid as VENUES,
    venue2.venue AS LOCATION,
    COUNT(*) AS number
FROM
(
    SELECT *
    FROM events
    WHERE eventdate < CURDATE()
    ORDER BY eventdate DESC
    LIMIT 5
) AS events
INNER JOIN venues as venue2 ON events.venueid=venue2.id
GROUP BY VENUES
ORDER BY number DESC

http://sqlfiddle.com/#!2/21ad85/37

于 2013-01-21T08:22:56.710 回答