1

table1:

name | map_id | reg_id 
abc  |  1     | 5
pqr  |  2     | 5
xyz  |  3     | 5

table2:

map_id | map_name | is_deleted
 1     | map1     |   0
 2     | map2     |   0

my sql query :

SELECT *
FROM   table1 t1
       LEFT JOIN table2 t2
              ON t1.map_id = t2.map_id
WHERE  t1.reg_id = 5
       AND t2.is_deleted = 0

what the above query does is stops me from retrieving record with map_id = 3 in table1.

how can i achieve this as well as 'is_deleted check' if the record exists in table2.

thanks in advance.

4

1 回答 1

3

您需要将is_deleted检查移至 JOIN:

select t1.name, t1.map_id, t1.reg_id,  -- replace select * with columns
  t2.map_name, t2.is_deleted
from table1 t1 
left join table2 t2 
  on t1.map_id = t2.map_id
  and t2.is_deleted = 0
WHERE t1.reg_id = 5;

请参阅SQL Fiddle with Demo。您当前的查询导致 theLEFT JOIN像 an 一样,INNER JOIN因为您将 theis_deleted作为 WHERE 子句的一部分。如果您将其移至 JOIN,那么您将返回该table2拥有的行,is_deleted=0并且您仍将返回来自table1where的所有行reg_id=5

于 2013-06-25T14:42:11.183 回答