简体   繁体   English

PHP MySQL合并具有相同列值的行

[英]PHP MySQL merge rows with same column value

I have a table looks like this: 我有一张桌子看起来像这样:

year | url                | view
-------------------------------
2016 | /document/item.pdf | 21
2015 | /document/item.pdf | 35
2014 | /document/item.pdf | 41

and I want build another table looks like this : 我想建立另一个表如下所示:

 url                | 2014 | 2015 | 2016
---------------------------------------
 /document/item.pdf | 41   | 35   | 21

I don't really now how I have to write my mysql query to do that. 我现在真的不是我必须如何编写mysql查询来做到这一点。 Thanks for your help :) 谢谢你的帮助 :)

  1. Query all data from your first table to PHP array, the array would be like: 将所有数据从第一个表查询到PHP数组,该数组将类似于:

     $data = [[2016, "/document/item.pdf", 21], [2015, "/document/item.pdf", 35], [2014, "/document/item.pdf", 41]]; 
  2. Traverse $data , make another associated array $result , whose key is url, value is an array of data with year and view: 遍历$data ,再创建另一个关联的数组$result ,其键为url,值是一个包含year和view的数据数组:

     $result = array(); foreach ($data as $value) { $result[$value['url']][$value['year']] = $value['view']; } 
  3. Traverse the new array, and write data back to MySQL 遍历新数组,并将数据写回到MySQL

You can try this: 您可以尝试以下方法:

 SELECT  url,
            MAX(IF(`year` = 2014 , view, NULL)) '2014',
            MAX(IF(`year` = 2015, view, NULL)) '2015',
            MAX(IF(`year` = 2016, view, NULL)) '2016'
    FROM    pub
    GROUP   BY url

you must make two table -> first to save files , second to save visits like this 您必须创建两个表->首先保存文件,其次保存这样的访问

Files Table 文件表

url_id | url
------------------------
1      |/document/item.pdf 
2      |/document/item.pdf 

Visits Table (url_id) is forign key from files table 访问表(url_id)是文件表中的外键

url_id | time
---------------
1       | 987907872     
2       | 987907872
2       | 987978272
2       | 987907872
2       | 987907872
1       | 987907872
1       | 987907872
1       | 987907872

======================== ========================

then you can check time by year in visits table to view number of visits of each URL 那么您可以在访问量表中按年份查看时间,以查看每个网址的访问量

May be it will help you 可能会对您有帮助

SELECT 
    url, 
    sum( if( year= '2014', view, 0 ) ) AS 2014,  
    sum( if( year= '2015', view, 0 ) ) AS 2015, 
    sum( if( year= '2016', view, 0 ) ) AS 2016 
FROM 
    pub
GROUP BY 
    url;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM