Mysql按其他表的结果排序(表2的COUNT行)

时间:2013-07-14 14:18:58

标签: php mysql

表1

SELECT * FROM page WHERE public = 1 order by*****results of table 2****** ASC

表2

SELECT * FROM abonnement where page_id = $page_id AND (date > NOW() OR gratis = 1)

COUNT ROWS TABLE 2并将其放在表1中订购......

3 个答案:

答案 0 :(得分:1)

select p.* 
from page p
inner join abonnement a on p.page_id = a.page_id
where p.public = 1 
and (a.date > NOW() OR a.gratis = 1)
order by count(a.id) desc

答案 1 :(得分:0)

听起来您需要group byleft outer join

SELECT p.*
FROM page p 
LEFT OUTER JOIN
     (SELECT page_id, COUNT(*) AS cnt
      FROM abonnement
      WHERE (date > NOW() OR gratis = 1)
      GROUP BY page_id
     ) a
     ON p.page_id = a.page_id
WHERE p.public = 1
ORDER BY a.cnt ASC;

如果第二个查询中没有匹配的行,left outer join可确保您不会丢失page中的任何行。

另请注意,我删除了条件page_id = $page_id。这被on子句取代。

我还建议在a.cnt子句中添加select,以便您真正看到计数。

答案 2 :(得分:0)

我认为他只需要在其中使用带有嵌套查询的更新语句......

update table t2
 set count = (select count(*) from table1 t1 where t1.filed=t2.field and other conditions)
where other table2 conditions