我有2个表,2个查询,我如何加入一个查询?

时间:2015-01-27 14:01:32

标签: mysql count

$sql = "SELECT id, user_id, category_id, title, content, thumb_url, img_url, height , engine, fuel, date_created 
from robots 
order by id DESC LIMIT  $offset, $rowsperpage ";

给了我所有的帖子和

$q = 'SELECT COUNT(robot_id) AS hits from hit_counter where robot_id =' . $_GET['id'];

3 个答案:

答案 0 :(得分:0)

使用左连接

SELECT r.id, r.user_id, r.category_id, r.title, r.content, r.thumb_url, r.img_url, r.height , r.engine, r.fuel, r.date_created ,
COUNT(c.robot_id) AS hits
from robots r
left join hit_counter c on(r.id = c.robot_id)
group by r.id
order by r.id DESC LIMIT  $offset, $rowsperpage 

答案 1 :(得分:0)

在两个表中使用以下查询和JOIN:

$sql = "SELECT id, user_id, category_id, title, content, thumb_url, img_url, height , engine, fuel, date_created, COUNT(hc.robot_id) AS hits 
from robots as rt LEFT JOIN hit_counter hc ON hc.robot_id = rt.id
where robot_id =" . $_GET['id']." order by id DESC LIMIT  $offset, $rowsperpage";

答案 2 :(得分:0)

要查看每个机器人的详细信息及其点击次数:

SELECT r.*,IFNULL(c.TotalCount,0)
FROM robots r LEFT JOIN
     (SELECT id,Count(*) as TotalCount
      FROM robots
      GROUP BY id) as c
ORDER BY r.id DESC
LIMIT  $offset, $rowsperpage