基于特定列数的订单表

时间:2015-06-23 13:27:46

标签: mysql sql laravel

我有一个projects表,其中包含以下列idproject_nameremix_of
项目可以是另一个项目的混音,正在重新混合的项目的ID存储在remix_of

id | project_name | remix_of
----------------------------
1  | 1st Project  | 0
2  | 2nd Project  | 0
3  | 3rd Project  | 2
4  | 4th Project  | 1
5  | 5th Project  | 2

我想查询所有项目,按重新混合的次数排序,在这种情况下它将是:

2nd Project | 2 remixes  
1st Project | 1 remix  
3rd Project | 0  
4th Project | 0  
5th Project | 0  

我使用的是MySQL,对整体SQL的经验很少。

3 个答案:

答案 0 :(得分:0)

wine regsvr32 file.dll or file.ocx

答案 1 :(得分:0)

您可以使用left join或相关子查询执行此操作:

select p.project_name,
       (select count(*) from projects pr where pr.remix_of = p.id) as remixes
from projects p 
order by remixes desc;

答案 2 :(得分:0)

要根据重新混音的数量进行查询,您可以按remix_of分组并获取COUNT(*)

SELECT remix_of AS project_id, COUNT(*) AS numRemixes
FROM myTable
GROUP BY project_id;

然后,如果您需要从原始表中获取值,只需执行JOIN。您可能希望左连接获得0值:

SELECT m.id, m.project_name, COALESCE(mt.numRemixes, 0) AS numRemixes
FROM myTable m
LEFT JOIN(
   SELECT remix_of AS project_id, COUNT(*) AS numRemixes
   FROM myTable
   GROUP BY project_id) mt ON mt.project_id = m.id
ORDER BY numRemixes DESC;