我创建了以下简单的DataModel
:
我用以下数据填充了表格:
1) 表客户
INSERT INTO test.customer
(CustomerName, Country, RegistrationDate)
VALUES
("Customer A","DE","2015-05-03"),
("Customer B","US","2015-07-25"),
("Customer C","US","2016-02-15"),
("Customer D","DE","2017-09-21"),
("Customer E","AU","2018-12-07");
2) 表订单
INSERT INTO test.orders
(idCustomer, PaymentMethod, OrderDate, OrderValue)
VALUES
("1","CreditCard","2015-05-04","500"),
("1","PayPal","2015-11-18","200"),
("3","PayPal","2017-09-04","300"),
("2","Invoice","2018-04-30","100");
3) 表标准
INSERT INTO test.criterias
(Country, MinimumOrderValue)
VALUES
("DE","300"),
("US","150"),
("AU","200");
之后,我创建了一个查询来根据条件 Country
和 OrderValue
获取Customers
及其Orders
:
SELECT
test.customer.idCustomer, CustomerName, Country,
test.orders.OrderValue
FROM test.customer
LEFT JOIN test.customer_info ON test.customer.idCustomer = test.customer_info.idCustomer
LEFT JOIN test.orders ON test.customer.idCustomer = test.orders.idCustomer
WHERE
Country = "US" AND OrderValue >= "150"
OR Country = "DE" AND OrderValue >= "300"
OR country = "AU" AND OrderValue >= "200";
到目前为止,所有这些都运行良好。
但是,不应将条件放在 SQL 查询中的 WHERE
子句中,而是应将它们存储在名为 Criterias
的单独表中。然后,查询应该从此表中获取数据并应用它们,就像上面的查询中现在所做的那样。
我必须在代码中更改哪些内容才能实现此目的?
最佳答案
不一定是答案;评论太长了...
一组有效的查询条件可能如下所示...
WHERE (country = "US" AND OrderValue >= 150)
OR (country = "DE" AND OrderValue >= 300)
OR (country = "AU" AND OrderValue >= 200);
...或者确实(尽管可能更慢)...
WHERE (country,ordervalue) IN(('US',150),('DE',300),('AU',200));
关于mysql - 从条件表中获取 WHERE 子句的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54350789/