You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL如何基于字段中的比较条件匹配数值查询价格?

Solution for Matching Numeric Input to Stored Condition Strings

Got it, let's tackle this problem. The core issue here is that your Condition_weight column stores text-based comparison rules, so we need a way to evaluate those rules against your input numeric value. Here are two practical approaches that match the "concise query" you're remembering:

1. Dynamic SQL (The "concise" approach you likely recall)

This method builds a SQL query on the fly by combining your input value with the stored condition string. It’s clean and directly reuses the logic in your table.

Example for SQL Server:

-- Replace @InputValue with your actual numeric input
DECLARE @InputValue INT = 30;
DECLARE @DynamicSQL NVARCHAR(MAX);

-- Build the query string
SET @DynamicSQL = N'
SELECT Price 
FROM Table_1 
WHERE Type = ''A'' 
AND ' + CAST(@InputValue AS NVARCHAR(10)) + ' ' + Condition_weight;

-- Execute the dynamically built query
EXEC sp_executesql @DynamicSQL;

Important Note:

Be cautious with dynamic SQL if your input comes from untrusted sources—it can expose you to SQL injection risks. Always validate or parameterize user inputs if this is a public-facing system.

2. CASE Expression (Safer, non-dynamic alternative)

If you want to avoid dynamic SQL entirely, you can map each stored condition to explicit logical checks using a CASE statement. This is more secure but requires updating the query if new conditions are added to the table.

Example:

DECLARE @InputValue INT = 30;

SELECT Price
FROM Table_1
WHERE Type = 'A'
AND CASE
    WHEN Condition_weight = '>50' THEN @InputValue > 50
    WHEN Condition_weight = '>10 & <50' THEN @InputValue > 10 AND @InputValue < 50
    WHEN Condition_weight = '<10' THEN @InputValue < 10
    ELSE 0 -- Ignore any unrecognized conditions
END = 1;

Both methods will return the correct Price for your input value. The dynamic SQL approach is the one you probably saw before—it’s concise and leverages the existing condition strings directly.

内容的提问来源于stack exchange,提问作者Chau Loi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:25:08