JOIN查询的行为不符合预期

时间:2012-10-08 06:34:28

标签: mysql sql

我正在处理一个行为不符合预期的查询,并希望能帮助我指出正确的方向。

TABLES 我有三个中央表由以下组成。

table_categories
- id (int)
- name (varchar)

table_events
- id (int)
- name (varchar)
- created (date time)

table_taxonomy
- cat_id (id from table_categories)
- event_id (id from table_events)
- type (varchar in this example always 'category')

目标 计算在每个类别中的特定日期之后创建的事件。结果应该是这样的:

COUNT   NAME    ID
3       Rock     1
2       Punk     3 

QUERY 这是我提出的查询。问题是结果并不关心创建的日期,而是抓住所有事件的关注时间。

SELECT COUNT(*) AS count,
            table_categories.name,
            table_categories.id
            FROM table_taxonomy
            INNER JOIN table_categories
            ON table_categories.id = table_taxonomy.cat_id
            LEFT JOIN table_events
            ON table_events.id = table_taxonomy.events_id
            WHERE table_taxonomy.type = 'category'
            AND table_taxonomy.cat_id IN(2,3)
            AND table_events.created > '2012-10-07 05:30:00'
            GROUP BY (table_categories.name)

2 个答案:

答案 0 :(得分:3)

尝试这个,只是在比较日期时进行小的改动:

SELECT COUNT(*) AS count,
            table_categories.name,
            table_categories.id
            FROM table_taxonomy
            INNER JOIN table_categories
            ON table_categories.id = table_taxonomy.cat_id
            LEFT JOIN table_events
            ON table_events.id = table_taxonomy.events_id
            WHERE table_taxonomy.type = 'category'
            AND table_taxonomy.cat_id IN(2,3)
            AND Date(table_events.created) > '2012-10-07 05:30:00'
            GROUP BY (table_categories.name)

答案 1 :(得分:1)

试试这个,

SELECT  c.ID, c.Name, COUNT(*)
FROM    table_categories a
        INNER JOIN table_taxonomy b
            ON a.id = b.cat_id
        INNER JOIN table_events c
            ON b.event_ID = c.ID
WHERE   c.created > 'dateHere' 
        -- AND .....                  -- other conditions here
GROUP BY    c.ID, c.Name