用PHP的MySql Tally系统

时间:2014-08-29 10:23:10

标签: php mysql

我试图将我在数据库中拥有的数据压缩成行,并将其点数计算在一起以查看最受欢迎的数据。

如果我有一个数据表,如:

   `data`
item1  item2
  1     
  1     2
  1     3
  1     3
  2     3

希望缩写版本为:

     `data_sum`
item1  item2  Tally
  1      2      2
  1      3      3
  2      3      1

我将如何实现这一目标?我在这里有点想法:

$popdata = mysql_query("SELECT * FROM data");
    while($add = @mysql_fetch_array($popdata)){         
        $qitem1 = "SELECT * FROM data_sum WHERE item1='".$add['item1']."'";
        $ritem1 = mysql_query($qitem1);
        if(mysql_num_rows($ritem1) > 0){
            $qitem2 = "SELECT * FROM data_sum WHERE item2='".$add['item2']."'";
            $ritem2 = mysql_query($qitem2);
            if (mysql_num_rows($ritem2) > 0){
                $sql = "UPDATE Tally=Tally + 1 WHERE item1='".$add['item1']."' AND item2='".$add['item2']."'";
                $update = mysql_query($sql);
            }
            else{
                $sql = "INSERT INTO data_sum (item1, item2) VALUES('$item1', '$item2')";
                $insert = mysql_query($sql);
            }
        else{
            $sql = "INSERT INTO data_sum (item1, item2) VALUES('$item1', '$item2')";
            $insert = mysql_query($sql);
        }

是的,我知道总计数比第一个表中的行多一个。我希望具有空列的行计入具有公共因子的两个计数。这个文件将经历数千行,所以我想要最高效率!谢谢!

2 个答案:

答案 0 :(得分:1)

您需要做的就是创建一个新表,然后将INSERT语句与GROUP BY' d SELECT语句合并。这COUNT()item1item2的次数相同,并将它们存储在新的计数表中。

有些事情:

INSERT INTO new_tally_table (item1, item2, Tally)
SELECT item1, item2, COUNT(*)
FROM table
GROUP BY item1, item2

编辑:
实际上重新阅读你问题的最后一点。想想你想要的是这样的:

SELECT item1, item2, COUNT(*)
FROM (
    SELECT i1.item1, i2.item2
    FROM table1 as i1
    INNER JOIN (
      SELECT DISTINCT item1, item2
      FROM table1 WHERE item2 IS NOT NULL
    ) as i2 ON (i1.item1 = i2.item1)
    WHERE i1.item2 IS NULL
  UNION ALL
    SELECT item1, item2
    FROM table1
    WHERE item2 IS NOT NULL
) as t
GROUP BY item1, item2

尽管如此,这可能是一种更好的写作方式。

答案 1 :(得分:0)

可能有一个更简单的解决方案,但我无法想到它......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,item1  INT NULL
,item2 INT NULL
);

INSERT INTO my_table (item1,item2) VALUES
(1     ,NULL),
(1     ,2),
(1     ,3),
(1     ,3),
(2     ,3);

SELECT x.item1
     , x.item2
     , COUNT(DISTINCT y.id) 
  FROM my_table x 
  JOIN my_table y 
    ON y.item1 = x.item1 
   AND (y.item2 = x.item2 OR y.item2 IS NULL)
   AND y.id <= x.id 
  JOIN 
     ( SELECT item1
            , item2
            , MAX(id) max_id 
         FROM my_table 
        GROUP 
           BY item1
            , item2
     ) z 
    ON z.item1 = x.item1 
   AND z.item2 = x.item2 
   AND z.max_id = x.id 
 WHERE x.item2 <> 0 
 GROUP 
    BY x.id;
+-------+-------+----------------------+
| item1 | item2 | COUNT(DISTINCT y.id) |
+-------+-------+----------------------+
|     1 |     2 |                    2 |
|     1 |     3 |                    3 |
|     2 |     3 |                    1 |
+-------+-------+----------------------+