按平台选择和计算不同的活动用户,并比较它们是否存在于其他表中

时间:2012-07-16 11:28:40

标签: php mysql sql database

我有大约六(6)个表,每个表都与userid链接。其中一个表是userinfo。用户信息包含用户详细信息,包括其商店平台(例如magento)

  1. Userinfo包含活动用户和非活动用户(活动用户在其他5个表中至少创建了一个活动)。
  2. 我想计算userinfo中具有magento平台的不同用户数,他们在任何其他表中都有记录。
  3. 目前,我可以使用ff代码计算其他五个表中不同数量的用户,但希望将其与userinfo表连接,以便我可以选择具有平台magento的活动用户。
  4. 不添加userinfo表意味着我无法按平台选择用户。
  5. 仅使用magento平台在userinfo表中选择用户将很容易,但这意味着我可以选择仅注册但不会继续在我的应用上创建活动的用户。

         $query3 = ("SELECT   COUNT(*)
         FROM     (
           SELECT userid FROM table1
           UNION SELECT userid FROM table2
           UNION SELECT userid FROM table3
           UNION SELECT userid FROM table4
           UNION SELECT userid FROM table5
           ) AS UserIDs");
           $result3 = mysql_query($query3) or die(mysql_error()); 
           $row3 = mysql_fetch_row($result3);
           echo "Number of distinct users in all tables  = ".$row3[0] ."<br />";
    
    
      **Table 1**
      Id    userid    name   adresss
    
      **Table 2**
      Id  Title   Sex   userid
    
      **Table 3**
      Id   userid   amount
    
      **Table 4**
      Id  price  promotion  userid   productid
    
      **Table  5**
      Id  userid   category   tax   weight
    
      **userinfo**
      Id  userid   username   password   platform
    

3 个答案:

答案 0 :(得分:1)

UNION子选择from my other suggestion上进行扩展,您可以使用JOIN表格UserInfo并获得您的明确计数。

SELECT   COUNT (DISTINCT ui.UserID))
FROM     (
           SELECT UserID FROM Table1
           UNION SELECT UserID FROM Table2
           UNION SELECT UserID FROM Table3
           UNION SELECT UserID FROM Table4
           UNION SELECT UserID FROM Table5
         ) AS id
         INNER JOIN UserInfo ui ON ui.UserID = id.UserID
WHERE    ui.Platform = 'Magento'

答案 1 :(得分:0)

我希望如此:

SELECT COUNT(DISTINCT ui.userid) as number
FROM userinfo ui
INNER JOIN table1 t1 ON (t1.userid = ui.userid) 
INNER JOIN table2 t2 ON (t2.userid = ui.userid) 
INNER JOIN table3 t3 ON (t3.userid = ui.userid) 
INNER JOIN table4 t4 ON (t4.userid = ui.userid) 
INNER JOIN table5 t5 ON (t5.userid = ui.userid) 
WHERE ui.platform = 'magento'

答案 2 :(得分:0)

如果你这样做:

    SELECT COUNT(DISTINCT ui.userid) as number
    FROM userinfo ui, table1 t1, table2 t2, table3 t3, table4 t4, table5 t5
    WHERE ui.platform = 'magento'
    AND t1.userid = ui.userid
    AND t2.userid = ui.userid 
    AND t3.userid = ui.userid 
    AND t4.userid = ui.userid
    AND t5.userid = ui.userid

如果不起作用,请尝试用SELECT ui。*替换SELECT COUNT(DISTINCT ui.userid) as number以查看。