2
SELECT 
    a.customers_id, b.name, b.office, b.username, a.serial_number, a.id
FROM 
    user_assets AS a
left JOIN 
    customers AS b ON 
        a.customers_id = b.id 
WHERE NOT 
        (b.username LIKE 'Warehouse') 
    AND (serial_number LIKE 'R8%' 
        OR serial_number LIKE 'LR%' 
        OR serial_number LIKE 'R9%')
GROUP BY
    a.customers_id
HAVING (COUNT(a.customers_id) >=2);

查询应该找到哪些用户拥有多台计算机。虽然每个用户只显示一条记录,但我如何显示 serial_number 列中的所有关联行?

编辑

删除and a.customers_id = a.customers_id,因为它是我正在尝试的东西,并且$by因为它不需要这个问题

4

2 回答 2

0

使用GROUP BY- 顾名思义 - 将结果分组(在您的情况下为user_assets' customer_id)。省略GROUP BY,它应该返回与您的条件匹配的每条记录。

我猜您真正想要的是一种按各自客户对记录进行分组的方法。您应该使用ORDER BY a.customer_id, 然后处理应用程序逻辑中的记录。

编辑一个工作示例是:

SELECT a.id,
       a.customers_id,           
       a.serial_number,
       b.name,
       b.office,
       b.username
  FROM user_assets AS a
  LEFT JOIN customers AS b
    ON a.customers_id = b.id 
 WHERE b.username != 'Warehouse'
   AND ( a.serial_number LIKE 'R8%'
    OR a.serial_number LIKE 'LR%'
    OR a.serial_number LIKE 'R9%' )
 ORDER BY a.customer_id

示例输出:

+----+--------------+---------------+-----+
| id | customers_id | serial_number | ... |
+----+--------------+---------------+-----+
|  3 |           11 | R8-xyz        | ... |
|  4 |           13 | R9-abc        | ... |
|  5 |           13 | R8-xyz        | ... |
|  6 |           13 | LR-abc        | ... |
| .. |           .. | ...           | ... |
| 37 |           21 | LR-abc        | ... |
| 38 |           21 | LR-def        | ... |
+----+--------------+---------------+-----+
于 2013-09-01T08:06:50.900 回答
0

You do not need left join and group by, but need simple inner join with a subquery in where-clause:

select b.customers_id, b.name, b.office, b.username, a.serial_number, a.id
from user_assets a, customers b 
WHERE a.customers_id = b.id 
  and b.username != 'Warehouse' 
  and (serial_number LIKE 'R8%' or serial_number LIKE 'LR%' or serial_number LIKE 'R9%')
  and (select count(1) from user_assets a1 
       where a1.customers_id=b.id
       and (serial_number LIKE 'R8%' or serial_number LIKE 'LR%' or serial_number LIKE 'R9%')  
      ) >= 2

Also you should consider creating and using directory table asset_types instead of such like-predicates on serial numbers. It would be more effective and a much better practise in general.

于 2013-09-01T08:15:06.537 回答