使用PHP对许多MySQL表进行分组和排序

时间:2015-11-08 02:44:54

标签: php mysql

我试图根据记录在下载表中出现的次数,以DESC顺序在多个表上输出一系列连接记录。

资源数据(resource_data):

----------------------------------------
| ID  |  Contributor ID |     Title    |
----------------------------------------
|  1  |        111      |  Resource A  |
|  2  |        222      |  Resource B  |
|  3  |        333      |  Resource C  |
|  4  |        222      |  Resource D  |
|  5  |        111      |  Resource E  |
----------------------------------------

投放人数据(contributor_data):

----------------------
|   ID  |  User Name |
----------------------
|  111  |   User X   |
|  222  |   User Y   |
|  333  |   User Z   |
----------------------

下载数据(download_data):

---------------------
|  ID | Resource ID |
---------------------
|  1  |      4      |
|  2  |      1      |
|  3  |      4      |
|  4  |      3      |
|  5  |      4      |
|  6  |      4      |
|  7  |      2      |
|  8  |      5      |
|  9  |      4      |
|  10 |      5      |
---------------------

排序时,数据应该是(不是格式化,只是内容):

4   222   Resource D   User Y  (5 records)
5   111   Resource E   User X  (3 records)
2   222   Resource B   User Y  (2 records)
3   333   Resource C   User Z  (1 record)
1   111   Resource A   User X  (1 record)

到目前为止,我已经有了这段代码,但它只发布了一条记录(应该有很多,基于查询限制为4条)。

SELECT * FROM resource_data, contributor_data, download_data 
WHERE resource_data.contributor_id=contributor_data.id 
AND download_data.resource_id=resource_data.id 
ORDER BY count(download_data.resource_id) DESC LIMIT 4

1 个答案:

答案 0 :(得分:1)

你想要的是一个GROUP BY子句来对download_data表中的那些资源id记录进行分组,就像这样......

SELECT contributor_data.id, resource_data.id, resource_data.title,
       contributor_data.username, COUNT(download_data.id) AS records
FROM resource_data
JOIN contributor_data
     ON resource_data.contributor_id = contributor_data.id
JOIN download_data
     ON resource_data.id = download_data.resource_id
GROUP BY download_data.resource_id
ORDER BY records DESC;

这将为您提供所需的结果,因为您现在可以根据GROUP BY对COUNT结果进行别名(因为ORDER BY在分组完成后发生)。

所以你的最终结果看起来更像你想要的......

+------+------+------------+----------+---------+
| id   | id   | title      | username | records |
+------+------+------------+----------+---------+
|  222 |    4 | Resource D | User Y   |       5 |
|  111 |    5 | Resource E | User X   |       2 |
|  222 |    2 | Resource B | User Y   |       1 |
|  333 |    3 | Resource C | User Z   |       1 |
|  111 |    1 | Resource A | User X   |       1 |
+------+------+------------+----------+---------+

这是SQLfiddle of the same ...