结合并使用来自两个不同表

时间:2016-03-08 10:12:57

标签: php mysql

  1. 我有一张桌子,上面有活动嘉宾的数据。我可以使用此查询检索已有人(membersAttended)的人数:

    SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`
        FROM `tmc_doorapp_guests` g
        LEFT JOIN `tmc_doorapp_events` e
        ON e.`id` = g.`event_id`
        WHERE `name1` REGEXP '^[0-9]+$'
        AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
        AND g.`checkin` = 1;
    
  2. 要检索我使用的成员总数(totalMembers):

    SELECT COUNT(DISTINCT `id`) AS `totalMembers`
        FROM `tmc_users`;
    
  3. 要获得参与总成员的百分比值totalPercent)成员,我使用PHP来进行两次查询,然后计算如下:< / p>

    $totalPercent = number_format(($membersAttended/$totalMembers*100),2);
    
  4. 我尝试将两个查询和百分比计算以类似的方式组合到下面,没有运气:

        SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`,
            COUNT(DISTINCT m.`id`) AS `totalMembers`,
            (`membersAttended` * 100 / `totalMembers`) AS `totalPercent`
            FROM `tmc_doorapp_guests` g, `tmc_users` m
            LEFT JOIN `tmc_doorapp_events` e
            ON e.`id` = g.`event_id`
            WHERE `name1` REGEXP '^[0-9]+$'
            AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
            AND g.`checkin` = 1;
    

    我也尝试扩展列:

        SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`,
            COUNT(DISTINCT m.`id`) AS `totalMembers`,
            (COUNT(DISTINCT g.`name1`) * 100 / COUNT(DISTINCT m.`id`)) AS `totalPercent`
            FROM `tmc_doorapp_guests` g, `tmc_users` m
            LEFT JOIN `tmc_doorapp_events` e
            ON e.`id` = g.`event_id`
            WHERE `name1` REGEXP '^[0-9]+$'
            AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
            AND g.`checkin` = 1;
    

    这给了我错误:

      

    错误代码:1054。'on clause'

    中的未知列'g.event_id'

    如何将这些SQL / PHP查询/计算合并到一个SQL查询中?

1 个答案:

答案 0 :(得分:0)

您可以使用子查询:

SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`,
       (SELECT COUNT(DISTINCT `id`) FROM `tmc_users`) AS `totalMembers`,
       COUNT(DISTINCT g.`name1`) * 100 / (SELECT COUNT(DISTINCT `id`)
                                          FROM `tmc_users`) AS `totalPercent`
FROM `tmc_doorapp_guests` g
LEFT JOIN `tmc_doorapp_events` e
ON e.`id` = g.`event_id`
WHERE `name1` REGEXP '^[0-9]+$'
AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND g.`checkin` = 1;