查询和回声解决方案? [关闭]

Having a hard time trying to work out how to make a mysql query and output the data into a table like the one I have made below.

Been playing around for a few days now with no luck, so any help would be much appreciated.

The image below shows my 3 database tables(in simple form) and what i'm trying to output using PHP/MYSQL.

The image also shows the total amount (count) of listings for each user for each category, I cant work out how i join it all together.

Hope this makes some sense!

http://img.photobucket.com/albums/v432/Winegums/table_zps2b57f483.jpg

Initially, you can do it like this,

SELECT  a.user_name,
        SUM(CASE WHEN c.cat_name = 'books' THEN 1 ELSE 0 END) books,
        SUM(CASE WHEN c.cat_name = 'videos' THEN 1 ELSE 0 END) videos
FROM    users a 
        LEFT JOIN downlods b
            ON a.user_ID = b.user_ID
        LEFT JOIN download_cats c
            ON b.cat_id = c.cat_id
GROUP BY a.user_name

But I guess you have unknown number of cat_name on your table. A Dynamic SQL is much more preferred,

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN c.cat_name = ''',
      cat_name,
      ''' THEN 1 ELSE 0 END) AS ',
      cat_name
    )
  ) INTO @sql
FROM download_cats;

SET @sql = CONCAT(' SELECT  a.user_name, ', @sql, ' 
                    FROM    users a 
                            LEFT JOIN downlods b
                                ON a.user_ID = b.user_ID
                            LEFT JOIN download_cats c
                                ON b.cat_id = c.cat_id
                    GROUP BY a.user_name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;