简体   繁体   中英

Return NULL for some values in multiple select SQL

I am working on a website in PHP and have this piece of code:

INSERT INTO items (producttype, firstcode, secondcode, brand, retailer, firstsize, secondsize)
          SELECT ?, productcodes.id, productcodes.id, brands.id, retailers.id, sizes.id, sizes.id
          FROM productcodes, brands, retailers, sizes
          WHERE LOWER(productcodes.code)=LOWER(?)
          AND LOWER(productcodes.code)=LOWER(?)
          AND LOWER(brands.name)=LOWER(?)
          AND LOWER(retailers.name)=LOWER(?)
          AND LOWER(sizes.id)=LOWER(?)
          AND LOWER(sizes.id)=LOWER(?)

But when I have an input like this

INSERT INTO items (producttype, firstcode, secondcode, brand, retailer, firstsize, secondsize)
          SELECT 3, productcodes.id, productcodes.id, brands.id, retailers.id, sizes.id, sizes.id
          FROM productcodes, brands, retailers, sizes
          WHERE LOWER(productcodes.code)=LOWER(NULL)
          AND LOWER(productcodes.code)=LOWER(NULL)
          AND LOWER(brands.name)=LOWER('Canada')
          AND LOWER(retailers.name)=LOWER('WE')
          AND LOWER(sizes.id)=LOWER('XL')
          AND LOWER(sizes.id)=LOWER(NULL)

Even though most columns can be null (this is checked earlier on in the code. It returns null (empty) for all columns if only one is actually returning 0 rows.

Thanks for all of your great tips/suggestions/explanations.

I have managed to get my code working by using this query, it might be a huge hack or really heavy for the server, but for now it works. If anyone has any suggestions to improve on this code, please leave a message.

INSERT INTO items 
        (producttype, 
         firstcode, 
         secondcode, 
         brand, 
         retailer, 
         firstsize, 
         secondsize)
SELECT 3, 
   IFNULL((SELECT productcodes.id 
           FROM   productcodes 
           WHERE  LOWER(productcodes.code) = LOWER(NULL)), NULL), 
   IFNULL((SELECT productcodes.id 
           FROM   productcodes 
           WHERE  LOWER(productcodes.code) = LOWER(NULL)), NULL), 
   IFNULL((SELECT brands.id 
           FROM   brands 
           WHERE  LOWER(brands.name) = LOWER('Canada')), NULL), 
   IFNULL((SELECT retailers.id 
           FROM   retailers 
           WHERE  LOWER(retailers.name) = LOWER('WE')), NULL), 
   IFNULL((SELECT sizes.id 
           FROM   sizes 
           WHERE  LOWER(sizes.size) = LOWER('XL')), NULL), 
   IFNULL((SELECT sizes.id 
           FROM   sizes 
           WHERE  LOWER(sizes.size) = LOWER(NULL)), NULL) 

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-2024 STACKOOM.COM