从条件表中获取 WHERE 子句的条件
Posted
技术标签:
【中文标题】从条件表中获取 WHERE 子句的条件【英文标题】:Getting conditions for WHERE clause from a table of criterias 【发布时间】:2019-01-24 16:04:23 【问题描述】:我创建了以下简单的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
的单独表中。然后查询应该从这个表中获取数据并应用它们,就像现在在上面的查询中一样。
我必须在我的代码中进行哪些更改才能实现这一点?
【问题讨论】:
当涉及多个表时,对所有列进行限定是一种很好的编程习惯。例如。test.orders.Country
... ?
提示 2:表别名!
为什么有些列得到适当的限定,而另一些却没有 - 似乎有点随机。
【参考方案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));
【讨论】:
【参考方案2】:根据上面的数据库模式,您必须创建一个字段客户表,它是主要的,它将与表名顺序映射。之后,您需要在查询中使用 Join 和 exists 子句。
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)
【讨论】:
【参考方案3】:您只需join
表或在where
子句中使用子查询。
后者更容易打字,所以:
WHERE EXISTS (SELECT 1
FROM Criterias cr
WHERE cr.Country = c.Country AND
cr.MinOrderValue <= o.OrderValue
)
【讨论】:
以上是关于从条件表中获取 WHERE 子句的条件的主要内容,如果未能解决你的问题,请参考以下文章