需要执行有条件的 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

此请求有问题(当我搜索"公司"关键字时(:

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

但它返回语法错误。

希望我足够清楚。

提前谢谢你!

如果您只想要商家名称中包含"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。 那只是为了抓住甚至没有商家的话题(

最新更新