Here is the query i am using to join two tables
SELECT `rf_popup`.*
FROM `rf_popup` LEFT JOIN
`g_metadata` ON (`rf_popup`.`name` = `g_metadata`.`name`)
WHERE (`g_metadata`.`g_id` = '2009112305475443' AND
`g_metadata`.`value` < rf_popup.cardinality OR
`g_metadata`.`g_id` IS NULL) AND
`category` IN ('S', 'all') AND
`field` IN ('descr', 'all') AND
`filler_type` IN ('F2', 'all')
ORDER BY `rf_popup`.`priority` DESC LIMIT 5
THIS IS TABLE rf_popup
+--------------+------------------------------------------------------------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------------------------------------------------------------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(200) | YES | | NULL | |
| text | text | YES | | NULL | |
| cardinality | int(11) | NO | | 1 | |
| field | varchar(200) | YES | | NULL | |
| category | enum('A','H','N','R','S','D','all') | YES | | NULL | |
| time_to_show | enum('START','END') | YES | | START | |
| filler_type | enum('F1','F2','F3','R1','R2','R3','all') | YES | | FILLER1 | |
| priority | int(11) | NO | | 0 | |
+--------------+------------------------------------------------------------------------
————+——+—–+———+—————-+
This is TABLE g_metadata
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| g_id | varchar(50) | YES | MUL | NULL | |
| name | varchar(50) | YES | MUL | NULL | |
| value | varchar(200) | YES | | NULL | |
| id | int(11) | NO | PRI | NULL | auto_increment |
+-------+--------------+------+-----+---------+----------------+
But the Query Returns Empty Result.but if i replace WHERE in query with AND. The query returns the results.Whats the difference??
There shouldn’t be any difference so i am confused
Simply speaking,
WHEREfilters the entire result set andJOIN ... ONfilters only the joined table.Since you have a
LEFT JOINhere, putting the filter in theONclause restricts the results returned for theg_metadatatable, but does not effect the results returned forrf_popup. That is, you will get null columns in the joined table (g_metadata) but the rows forrf_popupwill still be pulled.On the other hand, putting the filter in the
WHEREclause performs the join first, then filters the resulting (joined) result set. That is, rows that do not match the entireWHEREclause are simply not returned.Consider the following simplified examples:
A simple join:
returns
Filtering in the
ONclause:returns
Filtering in the
WHEREclause:returns