2013-07-14 31 views
0

表1mysql命令与其他表的结果(统计表2行)

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行表2,并把它在表1中ORDER BY .. ..

+3

我对什么是你想在这里做比较混乱。 – Prix

+0

使用加入: http://stackoverflow.com/questions/16231234/mysql-join-ordering-results-via-another-table-php – Klian

回答

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条款。

我也建议在select条款中包含a.cnt,以便您实际看到计数。

+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 
0

我认为他只需要使用一个UPDATE语句里面嵌套查询...

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