需要执行有条件的LIKE请求

时间:2018-07-05 14:50:11

标签: sql sql-like

我在这里用SQL苦苦挣扎

我制作了一个搜索栏,可以与sql中的三个不同行匹配。 问题是,这些行之一与另外两行不在同一张表中。

这是一个例子

 TABLE 1 : topics
 id  ||  name        ||  category || id_merchant
 1   ||  football    ||  Sports   || 1
 2   ||  marmalade   ||  cooking  || 2
 3   ||  Hitchcock   ||  cinema   || 3

 TABLE 2 : merchant
 id || merchant
 1  || NIKE
 2  || Cooking Corp
 3  || GoodFilms Corp

此请求的问题(当我搜索“ Corp”关键字时):

SELECT T.name, T.category, M.merchant 
FROM topics AS T, 
     merchant AS M 
WHERE T.name LIKE '%Corp%' 
   OR T.category LIKE '%Corp%' 
   OR M.merchant LIKE '%Corp%' 
  AND T.id_merchant = M.id

它返回其中所有名称为“ Corp”的商户,但是我只想检索与“ Corp”匹配的商户的主题

然后我尝试了这个:

SELECT T.name, T.category, M.merchant 
FROM topics AS T, 
     merchant AS M 
WHERE T.name LIKE '%Corp%' 
   OR T.category LIKE '%Corp%' 
   OR (SELECT M.merchant WHERE M.id = T.id_merchant) LIKE '%Corp%' 
  AND T.id_merchant = M.id

但是它返回语法错误。

希望我很清楚。

提前谢谢!

1 个答案:

答案 0 :(得分:2)

如果您只想要商家名称中带有“ Corp”的主题。
那那是我猜的唯一标准吗?

SELECT T.name, T.category, M.merchant 
FROM topics AS T
INNER JOIN merchant AS M ON (M.id = T.id_merchant)
WHERE M.merchant LIKE '%Corp%'

请注意,JOIN语法用于提高可读性。

顺便说一句,我注意到您喜欢使用OR。 因此,建议同时使用OR和AND时最好使用括号。 因为AND的计算优先于OR的计算。 因此m OR n AND x OR y被评估为m OR (n AND x) OR y

因此,包括其他OR:

SELECT T.name, T.category, M.merchant 
FROM topics AS T
LEFT JOIN merchant AS M ON (M.id = T.id_merchant)
WHERE (
   M.merchant LIKE '%Corp%' OR 
   T.name LIKE '%Corp%' OR 
   T.category LIKE '%Corp%'
)

(样本数据并不需要)
(请注意,这次使用了LEFT JOIN。这只是为了捕捉甚至没有商人的话题)

相关问题