php mysql sort by number of rows descending

情到浓时终转凉″ 提交于 2019-12-13 03:58:28

问题


can you help me

$sql="select * from table1 where id='1,2,3,4'";
{
 $sql2="select distinct column1 from table2 where column2='".$row['id']."' and left(date,10) BETWEEN '".$date_from."' AND '".$date_to."'";
 }

I need to sort $sql by number of rows descending for $sql2 by id


回答1:


If I understand you correctly, you want the results from $sql ordered by number of rows found by $sql2 for each row in $sql. This join should do that, it joins table2 and orders by the count, descending.

SELECT t1.id
FROM table1 t1
LEFT JOIN table2 t2
  ON t1.id=t2.column2
WHERE id IN (1,2,3,4)                     -- should it really be = '1,2,3,4'?
  AND LEFT(date,10) BETWEEN '2013-01-01' AND '2013-12-31'
GROUP BY t1.id
ORDER BY COUNT(DISTINCT t2.column1) DESC

An SQLfiddle to test with.



来源:https://stackoverflow.com/questions/16506952/php-mysql-sort-by-number-of-rows-descending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!