SQL LIKE条件使用另一个查询的结果

时间:2011-03-09 14:30:08

标签: sql sql-like

这样的事情是否有效

SELECT color
FROM rawdata 
WHERE color LIKE (
    SELECT TOP 1 color_condition 
    FROM rules
    WHERE rules_id=1
)

如果规则1的color_condition为B%,那么这会从rawdata返回color = 'Blue'的条目吗?

2 个答案:

答案 0 :(得分:1)

至少在SQL Server中它确实如此,看起来你正在使用TOP

中的那个
WITH rawdata(color) As
(
SELECT 'Blue' UNION ALL SELECT 'Red'
), rules(color_condition,rules_id) AS
(
SELECT 'B%',1
)
SELECT color FROM rawdata 
WHERE color LIKE (SELECT TOP 1 color_condition 
                  FROM rules WHERE rules_id=1)

返回

color
-----
Blue

答案 1 :(得分:0)

问题的答案是“是”,但我想知道是否是你的特定SQL结构引起了你的怀疑。就个人而言,我更喜欢看不到谓词被子查询打断。看看你是否觉得这更容易阅读:

SELECT D1.color 
  FROM rawdata AS D1
 WHERE EXISTS (
               SELECT * 
                 FROM rules AS R1
                WHERE D1.color LIKE R1.color_condition 
                      AND R1.rules_id = 1
              );