简体   繁体   中英

How To Remove Before Filter SQL QUERY

My Query :

SELECT * 
FROM tvn_Listing 
LEFT JOIN tvn_ListingOption ON (tvn_Listing.id = tvn_ListingOption.listings_id 
                                AND tvn_ListingOption.options_id = 12)

How to remove null record when I left join two table? My query returns a result that is not what the conditions specify.

If I am understanding your question correctly the problem is:

You get records from tvn_Listing table which have NULL values from the LEFT JOIN ed table tvn_ListingOption . Well you can check for null values in tvn_ListingOption table like:

SELECT * 
FROM tvn_Listing 
LEFT JOIN tvn_ListingOption ON (tvn_Listing.id = tvn_ListingOption.listings_id 
                                AND tvn_ListingOption.options_id = 12)
WHERE tvn_ListingOption.Id IS NOT NULL

Note that where you add the NOT NULL condition will affect the results (if options_id is NULLABLE)

test=# select * from tvn_Listing;
 id | nm 
----+----
  1 | A
  2 | B
(2 rows)

test=# select * from tvn_listingoption ;
 id | op 
----+----
  1 | A
  3 | B
    | D
(3 rows)

test=# select * from tvn_listing left join tvn_listingoption on tvn_listing.id=tvn_listingoption.id;
 id | nm | id | op 
----+----+----+----
  1 | A  |  1 | A
  2 | B  |    | 
(2 rows)

test=# select * from tvn_listing left join tvn_listingoption on tvn_listing.id=tvn_listingoption.id and tvn_listingoption.id is not null ;
 id | nm | id | op 
----+----+----+----
  1 | A  |  1 | A
  2 | B  |    | 
(2 rows)

test=# select * from tvn_listing left join tvn_listingoption on tvn_listing.id=tvn_listingoption.id where  tvn_listingoption.id is not null ;
 id | nm | id | op 
----+----+----+----
  1 | A  |  1 | A
(1 row)

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