多个表,同一列,使用where

时间:2012-07-21 23:46:58

标签: mysql

我遇到了这个问题的问题。它返回正确的total_names,total_events和total_misc,但其他三个总数(挂起的名称,事件和misc)是相同的数字,完全错误的数字。所有三个表都有created_by列。我做错了什么?

SELECT
    COUNT(DISTINCT names_revisions.id) AS total_names,
    COUNT(DISTINCT events_revisions.id) AS total_events,
    COUNT(DISTINCT misc_revisions.id) AS total_misc,
    SUM(if(names_revisions.status = "Pending", 1, 0)) AS total_pending_names, 
    SUM(if(events_revisions.status = "Pending", 1, 0)) AS total_pending_events, 
    SUM(if(misc_revisions.status = "Pending", 1, 0)) AS total_pending_misc
FROM 
    names_revisions,
    events_revisions,
    misc_revisions
WHERE 
    :user_id IN (names_revisions.created_by, events_revisions.created_by, misc_revisions.created_by)

2 个答案:

答案 0 :(得分:2)

IN()子句不会像您尝试使用它一样工作。您的三个表之间需要JOIN个条件,<table> = :user_id中需要三个WHERE

SELECT
    COUNT(DISTINCT names_revisions.id) AS total_names,
    COUNT(DISTINCT events_revisions.id) AS total_events,
    COUNT(DISTINCT misc_revisions.id) AS total_misc,
    SUM(if(names_revisions.status = "Pending", 1, 0)) AS total_pending_names, 
    SUM(if(events_revisions.status = "Pending", 1, 0)) AS total_pending_events, 
    SUM(if(misc_revisions.status = "Pending", 1, 0)) AS total_pending_misc
FROM 
    names_revisions,
    JOIN events_revisions ON names_revisions.created_by = events_revisions.created
    JOIN misc_revisions ON names_revisions.created_by = misc_revisions.created
WHERE 
  names_revisions.created_by = :user_id
  OR events_revisions.created_by = :user_id
  OR misc_revisions.created_by = :user_id

答案 1 :(得分:1)

您正在加入表格,而不是单独选择计数。对3个表而不是连接使用单独的查询会更快

SELECT
    names.total as toal_names,
    names.pending as total_pending_names,
    misc.total as total_misc,
    misc.pending as total_pending_misc,
    events.total as total_events,
    events.pending as total_pending_events
FROM 
    (
        SELECT 
            COUNT(names_revisions.id) AS total,
            SUM(if(names_revisions.status = "Pending", 1, 0)) AS pending
        FROM names_revisions
        WHERE names_revisions.created_by = :user_id
    ) as names,
    (
        SELECT 
            COUNT(misc_revisions.id) AS total,
            SUM(if(misc_revisions.status = "Pending", 1, 0)) AS pending
        FROM misc_revisions
        WHERE misc_revisions.created_by = :user_id
    ) as misc,
    (
        SELECT 
            COUNT(events_revisions.id) AS total,
            SUM(if(events_revisions.status = "Pending", 1, 0)) AS pending
        FROM events_revisions
        WHERE events_revisions.created_by = :user_id
    ) as events