2016-05-06 50 views
-1

的计数的MySQL我有一个表为了通过一列

tid item 
1 k1 
1 k1 
1 k1 
1 k2 
1 k2 
2 k1 
2 k3 
3 k2 
3 k1 
3 k4 

我想从项目总订购,所以K1出现5次,,比K2出现3次,K3和K4一次。我想通过tid asc命令它,并计数项目desc。

我尝试这个查询,

SELECT * 
FROM `tes2` 
order by count(id_item) desc 

,但它只是返回1行。

tid item 
1 k1 

如何获取所有数据?

,我想输出是这样

tid item 
    1 k1 
    1 k1 
    1 k1 
    1 k2 
    1 k2 
    2 k1 
    2 k3 
    3 k1 
    3 k2 
    3 k4 

通过项目的数量,使得它的排序。

+0

尝试使用具有 – Mojtaba

+0

请提供您的问题与表期望的输出。 – trincot

+0

@trincot我已经添加它,THX的男人.. –

回答

1

您可以使用子查询来获取每个项目的计数,然后加入该主表上的项目,以便您可以通过计数命令做到这一点。 下面是MSSQL,但你应该能够在你的MySQL查询中使用这个解决方案。

设置测试 -

DECLARE @Test TABLE 
( 
    tid int, 
    tem VARCHAR(5) 
) 

INSERT into @Test (tid, item) VALUES (1, 'k1'); 
INSERT into @Test (tid, item) VALUES (1, 'k1'); 
INSERT into @Test (tid, item) VALUES (1, 'k1'); 
INSERT into @Test (tid, item) VALUES (1, 'k2'); 
INSERT into @Test (tid, item) VALUES (1, 'k2'); 
INSERT into @Test (tid, item) VALUES (2, 'k1') 
INSERT into @Test (tid, item) VALUES (2, 'k3'); 
INSERT into @Test (tid, item) VALUES (3, 'k2'); 
INSERT into @Test (tid, item) VALUES (3, 'k1'); 
INSERT into @Test (tid, item) VALUES (3, 'k4'); 

查询 -

SELECT t.tid,t.item 
FROM @Test t 
JOIN (SELECT t2.Item, COUNT(*) AS ItemCount FROM @Test t2 GROUP BY t2.Item) counts ON counts.Item = t.Item 
ORDER BY counts.ItemCount DESC, t.tid ASC 

输出 -

tid item 
    1 k1 
    1 k1 
    1 k1 
    2 k1 
    3 k1 
    1 k2 
    1 k2 
    3 k2 
    2 k3 
    3 k4 
+0

这是正确的solution..OP也希望通过TID ASC下令临时表.. – cableload

+0

我可以做我想要的输出,而不创建临时表? –

+0

当然,临时表就是这个例子。使用我发布的查询并将您的表换出@Test。 – Tom

0

试试这个:

SELECT count(id_item), field1, field2, field3 
FROM `tes2` 
order by 0 desc