需要做一个有条件的 LIKE 请求

Need to do a conditionnal LIKE request

我在这里苦苦挣扎 SQL

我制作了一个可以匹配 sql 中三个不同行的搜索栏。 问题,这些行之一与其他两行不在同一 table 中。

这是一个例子

 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

它 returns 所有 "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

但它 returns 语法错误。

希望我说得够清楚了。

提前致谢!

如果您只想要商家名称中包含 '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,就是为了把连商户都没有的topic也抓起来)