Home >Backend Development >PHP Tutorial >怎么按投票数来排序?

怎么按投票数来排序?

WBOY
WBOYOriginal
2016-06-20 12:28:551764browse

表tp
toupiao_id      name       ........
       1              张三
       2              李四

表tp1
id           toupiao_id         ip
1                  1               .......
1                  1               .......
1                  2               .......
1                  2               .......
1                  2               .......

循环表tp
$sql = "SELECT * FROM ".$fdyu->table('tp')." ".$sql_where." order by toupiao_id asc";//// 请问order by这个怎么写可以按表tp1里的toupiao_id数的多少来排列
$res = $db->query($sql);
$arr = array();

比如,李四有3票,张三有2票,那么在循环tp表的时候,李四显示在前面,张三显示在后面


回复讨论(解决方案)

 最近天气一冷一热的
你这种情况我一般会把数量缓存到表1中,每次投票更新一下

现在已经没放了,有什么办法解决

对 toupiao_id 分组求 count

帮忙写一下,谢谢^_^

可以这样写:

select tp1.toupiao_id, count(*) as total_vote from tp1 left join tp on tp1.toupiao_id = tp.toupiao_id group by tp1.toupiao_id order by total_vote desc;

select a.*,b.num from tp as a left join (select toupiao_id,count(*) as num from tp1 group by toupiao_id) as b on a.toupiao_id=b.toupiao_id order by b.num desc;

后来发现这样统计和排序票数,数据库到后面票数多的时候受不了,后来还是改成1楼说的那样了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn