问题描述
我正在尝试编写Select语句以比较两列。
我有这些表:
表1
Code Name
-----------------
ABC Product1
DEF Product2
GHI Product3
和表2
Code2 Price
-------------
ABC-1 4
DEF-2 6
GHI-5 9
我希望它退回
Name Price
------------------
Product1 4
Product2 6
Product3 9
但是我的语句返回空
Select Name,Price
From Table1,Table2
Where '%' + Code + '%' LIKE Code2
我看过类似的问题,但不确定代码中有什么问题
解决方法
LIKE
模式始终位于LIKE
的右边:
Select t1.Name,t2.Price
From Table1 t1 join
Table2 t2
on t2.Code2 like '%' || t1.Code || '%'
注意:
- 从不在
FROM
子句中使用逗号。 - 始终使用正确的,明确的,标准,可读的
JOIN
语法。 - 使用多个表限定查询中的所有列引用,以便您(和其他人)知道列的来源。
- 字符串连接运算符为
||
。 - 您想要的模式可能更像
t2.Code2 like t1.Code || '-%'
。