简体   繁体   中英

MySQL query logic assistance

I have a MySQL query where I need to be able to put in a set of several serial numbers, and get any that match (and corresponding data) from the database.

The below query works perfectly without the last WHERE clause regarding the freight forwarder ID, but as soon as I add it, it gives me the correct result set (23 records) PLUS 217 more (240 total) of the same serial numbers with a freight forwarder ID of NULL. I thought based on how I wrote it, that it should show only those records within the result set once, whether the Freight forwarder is NULL or if not, then the Freight Forwarder name when it is not null.

Here's the query:

SELECT serialnumbers.serialNumber, serialnumbers.stolenItem,
serialdeals.ProfitCenterNo,
CASE WHEN (serialdeals.FFIDLookup IS NULL) THEN NULL ELSE freightforwarders.FreightFwderName END,
serialdeals.ProdIDLookup,
brands.brandName, stockitems.model,
serialdeals.EANIDLookup,
serialdeals.DealCancelled, serialdeals.DateOfDeal, serialdeals.DateEntered,
wb_users.UserName 
FROM serialnumbers,serialdeals,wb_users,stockitems, brands, freightforwarders 
WHERE serialnumbers.serialNumber IN 
(990003084921374,990003086488406,990003085170252,990003085303135,990003086126782,990003086603822,990003083637393,990003083743738,990003086609910,990003083745402,990003083610325,990003064133834,990003085044226,990003085489520,990003083334256,990003085932289,990003083357117,990003083614855,990003083697348,990003086421183,990003086564933,990003086628977,990002899811317,990002895682506)
AND  ((serialnumbers.DealIDLookup=serialdeals.DealUniqID) 
   OR (serialnumbers.DealIDLookup IS NULL AND serialnumbers.stolenItem=1))  
AND serialdeals.UserID=wb_users.UserId 
AND serialdeals.ProdIDLookup=stockitems.BaseStockItemId 
AND stockitems.brandID=brands.brandID 
AND ( serialdeals.FFIDLookup IS NULL 
   OR serialdeals.FFIDLookup=freightforwarders.FFID)

It seems to keep showing me more of the same serial number repeated with NULL Freight forwarders. None of these SNs were with NULL deal ID and stolenItem=1.

Can anyone explain where my logic is off and how to fix the SQL statement to work the way I want it to (ie to show all serial numbers and deals even if freight forwarder is NULL, but should only be those 23 showing one time each)

Thanks in advance!

Instead of the

AND ( serialdeals.FFIDLookup IS NULL 
   OR serialdeals.FFIDLookup=freightforwarders.FFID)

You need LEFT JOIN

FROM serialnumbers,wb_users,stockitems, brands, 
     serialdeals LEFT JOIN freightforwarders ON serialdeals.FFIDLookup=freightforwarders.FFID

In general it is bett4er to move conditions from WHERE section to FROM and define JOINs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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