简体   繁体   English

2个表SQL查询的怪异结果

[英]2 table SQL Query weird results

Ok this is driving me nuts, I need to write an SQL query that will grab product information from 2 tables. 好的,这真让我发疯,我需要编写一个SQL查询,该查询将从2个表中获取产品信息。 The first table 'products' contains the productId, productname, quantityperunit and unitprice. 第一个表“产品”包含productId,productname,permanentperunit和unitprice。 Now I can search by productname and categoryname individually, but when I try to combine the 2 I get crazy results, Here's the query: 现在,我可以分别按产品名称和类别名称进行搜索,但是当我尝试将两者结合使用时,会得到疯狂的结果,这是查询:

"SELECT DISTINCT productId, productname, quantityperunit, unitprice FROM products pr,
categories ca WHERE pr.categoryID = ca.categoryID AND ProductName LIKE '%" + searchTerm + "%'
OR CategoryName LIKE '%" + searchTerm + "%'

excuse the java style in there, here it is formatted better: 请原谅其中的Java样式,这里的格式更好:

SELECT DISTINCT productId, productname, quantityperunit, unitprice FROM products pr,
categories ca WHERE pr.categoryID = ca.categoryID AND ProductName LIKE '%Tofu%'
OR CategoryName LIKE '%Tofu%'

any help would be appreciated. 任何帮助,将不胜感激。

I cannot tell for sure what you mean by "crazy reslust", but I guess you got many more rows than you expected. 我无法确定您所说的“疯狂刷新”是什么意思,但我想您得到的行比您预期的要多。 Add parenthesis : 添加括号:

WHERE pr.categoryID = ca.categoryID AND (ProductName LIKE '%Tofu%'
OR CategoryName LIKE '%Tofu%')

Your LIKE s in your two sample queries are different. 您的两个示例查询中的LIKE不同。

LIKE '%Tofu%' is very different from LIKE 'Tofu' . LIKE '%Tofu%'LIKE 'Tofu'非常不同。

The % acts like a wildcard, so LIKE '%Tofu%' matches Big chunk o' Tofu and stuff but LIKE 'Tofu' will not match that - it will ONLY match Tofu . %行为就像通配符,因此LIKE '%Tofu%'匹配Big chunk o' Tofu and stuffLIKE 'Tofu'则不匹配-仅匹配Tofu

Which did you mean? 你是什​​么意思

(also, I agree with the guy who mentioned you should check your brackets) (另外,我同意提到您应该检查一下括号的那个人)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM