按另一个表中的数据排序行

时间:2011-09-05 10:19:18

标签: php mysql sql-order-by

如果我有两张桌子,

首先table1

id   name

1    John
2    Andrew
3    Serj
4    Mike
5    Adam

和第二个table2

 user_id  count  date

  2       0      01-09-2011...
  5       9      05-09-2011...
  1       5      05-09-2011...
  3       7      04-09-2011...

如何从table1中选择用户,并按countdate table2来自1 -- Adam ( count = 9 , date = 05.. ) 2 -- John ( count = 5 , date = 05.. ) 3 -- Serj ( count = 7 , date = 04.. ) 4 ... 5 ... ... (DESC)

的值进行排序

我想要的结果:

{{1}}

如果无法实现,或者难以获得我想要的结果(请参阅我的结果),那么只需按计数和日期排序。

4 个答案:

答案 0 :(得分:1)

select * from table1 t1 
join table2 t2 on t1.id = t2.user_id 
order by date desc, count desc

答案 1 :(得分:1)

使用JOIN。

SELECT name from table1
JOIN table2 ON table1.id = table2.user_id
ORDER BY table2.count, table2.date DESC

答案 2 :(得分:1)

请试试

select * from table1 t1 
join table2 t2 on t1.id = t2.user_id 
order by date, count desc

答案 3 :(得分:0)

使用INNER JOIN

   SELECT t1.name, t2.count, t2.date
   FROM table1 AS t1 INNER JOIN table2 AS t2 
   ON t1.id = t2.user_id
   ORDER BY t2.count DESC, t2.date DESC;