【问题标题】:php mysql sort by number of rows descendingphp mysql按行数降序排序
【发布时间】:2013-05-12 11:39:24
【问题描述】:

你能帮我吗

$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."'";
 }

我需要按 $sql2 的行数按 id

降序对 $sql 进行排序

【问题讨论】:

  • 为什么要将第二个查询包装在 {} 中?

标签: php mysql sorting distinct


【解决方案1】:

如果我理解正确,您希望$sql 的结果按$sql2$sql 中的每一行找到的行数排序。这个连接应该这样做,它连接 table2 并按计数排序。

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.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-11-08
  • 2011-06-28
  • 1970-01-01
  • 2014-02-16
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
相关资源
最近更新 更多