简体   繁体   中英

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. Thanks for your help :)

  1. Query all data from your first table to PHP array, the array would be like:

     $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:

     $result = array(); foreach ($data as $value) { $result[$value['url']][$value['year']] = $value['view']; } 
  3. Traverse the new array, and write data back to 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 | 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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