我创建了以下简单的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");
然后,我根据条件Customers
和Orders
创建了一个查询,以获取Country
及其OrderValue
:
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
的单独表中。然后,查询应该从该表中获取数据,并像上面的查询中一样完全应用它们。
要实现此目的,我需要在代码中进行哪些更改?
答案 0 :(得分:1)
不一定是答案;评论太久了...
一组有效的查询条件可能看起来像这样...
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));
答案 1 :(得分:1)
根据上述数据库架构,您必须制作一个主要客户字段客户表,它将按照表名顺序进行映射。之后,您需要在查询中使用Join and exist子句。
select c.cutomerId, c.customerName, c.country, o.orderValue from customer c, order o where c.customerId = o.customerId and
exists (select * from criteria cr where cr.country = c.country and o.order >= cr.MinimumOrderValue)
答案 2 :(得分:0)
您只需join
表或在where
子句中使用子查询。
后者更易于键入,因此:
WHERE EXISTS (SELECT 1
FROM Criterias cr
WHERE cr.Country = c.Country AND
cr.MinOrderValue <= o.OrderValue
)