1

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
  • Please don't make us guess your requirements. And please provide some insights to what you have tried so far. As it stands, your question looks suspiciously like a "do my homework" question (which typically get closed rather quickly) Commented Feb 28, 2017 at 10:28

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

1
  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

1 Comment

I was focused on a mysql query but it works fine with an array. Thanks Martin.
0

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

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.