MySQL Returns All Rows When field = 0

冷暖自知 提交于 2020-01-07 05:24:05

问题


I've seen a few questions on here very similar to this however I have not found an answer specific to what I believe my problem to be.

I have two tables, subcompanies and presets. The two tables are linked together through an ID, CntRefID and PresetIDFoxPro. I want to select all of the text from the Preset table's text column when the ID's matchup.

This works flawlessly when the CntRefID has a number in it. However, if it is 0 then every single field from the presets text column is returned instead.

This is my query text;

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

I cannot get my head round why every field is selected. I have tried 0 in quotes and without quotes, I have also seen it could be due to one field being an Integer and one being a Char (mySQL returns all rows when field=0). Both my fields are integers however.


回答1:


All rows from the presets table are returned due to the OR CntRef='0' condition (where CntRef is 0).

This is because your existing where clause can be paraphrased (ignoring the PresetReferenceFoxPro condition) as:

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.

If you want to return subcompanies records even when they don't have a match on presets, then you need to use a LEFT OUTER JOIN - like so:

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

I'm assuming that PresetReferenceFoxPro is on the presets table - it would clarify the query to add table aliases to each of the columns in the SELECT clause, but I don't know which columns come from which tables.




回答2:


You need to change your "where" by removing "or" or add more conditions

 WHERE (CntRef=PresetIDFoxPro) .... other conditions

Just for example



来源:https://stackoverflow.com/questions/33802918/mysql-returns-all-rows-when-field-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!