MySQL Returns 字段 = 0 时的所有行

MySQL Returns All Rows When field = 0

我在这里看到了一些与此非常相似的问题,但是我没有找到我认为我的问题所在的具体答案。

我有两个 table,subcompaniespresets。两个 table 通过 ID CntRefIDPresetIDFoxPro 链接在一起。当 ID 匹配时,我想 select Preset table 的文本列中的所有文本。

CntRefID 中有一个数字时,这可以完美地工作。但是,如果它为 0,则返回 presets 文本列中的每个字段。

这是我的查询文本;

myQuery.CommandText =   
"SELECT CompanyID, CompanyName, PresetText, InvHeader, Prefix, NextBnum  
FROM sdcdatabase.sdcsubcompanies, sdcdatabase.presets   
WHERE (CntRef=PresetIDFoxPro OR CntRef='0') AND PresetReferenceFoxPro=3";

我不明白为什么每个字段都是 selected。我试过在引号中使用 0 和不使用引号,我还发现这可能是由于一个字段是整数而另一个字段是字符 (mySQL returns all rows when field=0)。但是我的两个字段都是整数。

您需要通过删除 "or" 或添加更多条件

来更改您的 "where"
 WHERE (CntRef=PresetIDFoxPro) .... other conditions

举个例子

由于 OR CntRef='0' 条件(其中 CntRef 为 0),presets table 中的所有行都被 returned。

这是因为您现有的 where 子句可以解释为(忽略 PresetReferenceFoxPro 条件)为:

I want all records from the subcompanies table and either any matching records from the presets table, or all records from the presets table where CntRef is 0 on the subcompanies table.

如果你想要 return subcompanies 记录,即使它们在预设上没有匹配项,那么你需要使用 LEFT OUTER JOIN - 像这样:

SELECT CompanyID, CompanyName, PresetText, InvHeader, Prefix, NextBnum 
FROM sdcdatabase.sdcsubcompanies as s 
LEFT OUTER JOIN sdcdatabase.presets as p 
ON s.CntRef=p.PresetIDFoxPro AND p.PresetReferenceFoxPro=3

我假设 PresetReferenceFoxPropresets table 上 - 它会澄清向 table 中的每个列添加别名的查询=25=] 子句,但我不知道哪些列来自哪个 tables.