0

I am using following query:

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

But with this query I am getting multiple records for each users if they have more than one work_orders. What should I do to only list users once which have more than one work_orders?

4

4 回答 4

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
于 2012-06-12T19:54:38.617 回答
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
于 2012-06-12T19:55:46.853 回答
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
于 2012-06-12T19:55:50.920 回答
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
于 2012-06-12T19:58:58.723 回答