我们有 2 张 table :
客户:
select name, i_customer from Customers limit 5;
| Western Refinishers (Pty) Ltd | 2265 |
| Westonaria Motor Investments (Pty) Ltd | 1949 |
| Wild Break 1479 cc | 1225 |
| Workshop On Wheels (Pty) Ltd | 2582 |
| Wynberg Panelbeaters And Spray Painters | 2471 |
自定义字段值:
select i_customer, i_custom_field, value
from Custom_Field_Values
where i_custom_field in (14,15,16,17,18) limit 5;
+------------+----------------+-------+
| i_customer | i_custom_field | value |
+------------+----------------+-------+
| 64 | 14 | 101 |
| 321 | 14 | 101 |
| 321 | 16 | 2233 |
| 1519 | 14 | 102 |
| 1529 | 14 | 102 |
+------------+----------------+-------+
同一客户可以在 Custom_Field_Values 表中拥有多条记录。例如,i_custom_field 14 和 16。
我需要检索一个报告,该报告仅针对 i_custom_field 编号为 16、17、18 的记录返回所有客户唯一名称和 Custom_Field_Values.values。
如果客户在 (16,17,18) 中没有包含 i_custom_field 的记录,只需将其值替换为空字符串即可。
最佳答案
您可以尝试像这样的 LEFT JOIN:
SELECT c.name, cfv.value
FROM customer c
LEFT JOIN Customer_Field_Values cfv
ON c.i_customer = cfv.i_customer
AND cfv.i_custom_field > 15
AND cfv.i_custom_field < 19;
关于mysql - 从具有重复值的表中返回所需结果的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912496/