左连接并获取连接表上的总记录

时间:2012-06-12 19:52:16

标签: mysql

我正在使用以下查询:

SELECT `users`.`id` as id 
FROM (`users`) 
    LEFT JOIN `work_orders` 
        ON `users`.`id` = `work_orders`.`assigned_to` 
WHERE (work_orders.status = 'approved' 
        OR work_orders.status = 'scheduled' 
        OR work_orders.status = 'published') 
    AND work_orders.is_paid = 0 
ORDER BY `users`.`id` DESC 
LIMIT 30

但是对于此查询,如果每个users有多个work_orders,我会收到多条记录。我应该怎么做只列出users 一次哪个有多个work_orders

4 个答案:

答案 0 :(得分:1)

您可以使用DISTINCT子句:

SELECT DISTINCT(users.id) as id FROM (`users`) LEFT JOIN `work_orders` ON `users`.`id` = `work_orders`.`assigned_to` WHERE (work_orders.status = 'approved' OR work_orders.status = 'scheduled' OR work_orders.status = 'published') AND work_orders.is_paid = 0 ORDER BY `users`.`id` DESC LIMIT 30

答案 1 :(得分:0)

您可以添加GROUP BY语句按用户的ID进行过滤,因为这是您感兴趣的所有内容。

SELECT `users`.`id` as id 
FROM (`users`) LEFT JOIN `work_orders` ON `users`.`id` = `work_orders`.`assigned_to` 
WHERE (work_orders.status = 'approved' 
  OR work_orders.status = 'scheduled' 
  OR work_orders.status = 'published') 
  AND work_orders.is_paid = 0 
GROUP BY `users`.`id`
ORDER BY `users`.`id` DESC LIMIT 30

答案 2 :(得分:0)

尝试使用GROUP BY

SELECT `users`.`id` as id 
  FROM (`users`) 
  LEFT JOIN `work_orders` 
    ON `users`.`id` = `work_orders`.`assigned_to` 
 WHERE ( work_orders.status = 'approved' 
       OR work_orders.status = 'scheduled' 
       OR work_orders.status = 'published' ) 
   AND work_orders.is_paid = 0 
GROUP BY `users`.`id` DESC 
LIMIT 30

答案 3 :(得分:0)

SELECT `users`.`id` as id 
  FROM (`users`) 
  WHERE exists ( select 1 from `work_orders` where work_orders.status 
                     in  ('approved' ,'scheduled' ,'published' ) 
                     AND work_orders.is_paid = 0 
                     and `work_orders`.`assigned_to` =`users`.`id` )
 ORDER BY `users`.`id` DESC 
 LIMIT 30