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
因此问题无法解决
答案 0 :(得分: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 | ... |
+----+--------------+---------------+-----+
答案 1 :(得分:0)
您不需要left join
和group by
,但需要在where子句中使用子查询进行简单的内连接:
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
另外,您应该考虑创建和使用目录表asset_types
而不是序列号上的like
- 谓词。一般来说,它会更有效,也是一种更好的做法。