PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] How to filter SQL results when the referenced table can be empty?

 October 29, 2022     exists, left-join, sql, sqlite, where-clause     No comments   

Issue

I have a query which selects from different tables, then uses a WHERE clause to filter the items. The clause looks like this:

WHERE allItems.NumID != (SELECT RelatedNumID FROM allRelated WHERE NumID = allItems.NumID)

This works fine when allRelated table isn't empty. But when it's empty, I get 0 results from the query.

I have tried to use NOT IN instead of !=. It returns result when allRelated is empty, but doesn't filter the results when allRelated isn't empty:

WHERE allItems.NumID NOT IN (SELECT RelatedNumID FROM allRelated WHERE NumID = allItems.NumID)

I also tried to join the tables, but I get the same result as with NOT IN:

LEFT JOIN allRelated ON allItems.NumID = allRelated.NumID
WHERE allRelated.NumID IS NOT NULL

How should I write the query so that it works for both empty and non-empty allRelated table?

P.S. I'm using SQLite.


Solution

Try with NOT EXISTS:

WHERE NOT EXISTS (
  SELECT 1 
  FROM allRelated 
  WHERE allRelated.NumID = allItems.NumID
    AND allRelated.RelatedNumID = allItems.NumID
) 

or, change the condition in the WHERE clause of the LEFT join to IS NULL:

LEFT JOIN allRelated 
ON allItems.NumID = allRelated.NumID AND allRelated.RelatedNumID = allItems.NumID
WHERE allRelated.NumID IS NULL


Answered By - forpas
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing