Jump to content

LEFT JOIN not working well with WHERE clause


jkkenzie

Recommended Posts

There is a record (tbl_business.appformno LIKE '%3133%' ) which actually exists but there is no Record for it on the table  tbl_activities.appformno:

 

The following search does not show the above record, yet it should show because am using LEFT JOIN

 

SELECT tbl_business.id AS `ID` , tbl_business.appformno AS `Form No` , tbl_business.bid AS `BID` , tbl_business.company AS `Business Name` , tbl_business.pobox AS `Address` , tbl_business.postalcode AS `Postal Code` , tbl_business.plotno AS `Plot No.` , tbl_business.zonecode AS `Zone Name/Code` , tbl_activities.act_code AS `Activity Code` , tbl_business.ne AS `N/E`
FROM tbl_business
LEFT JOIN tbl_activities ON tbl_business.appformno = tbl_activities.appformno
WHERE tbl_business.appformno LIKE '%3133%'
AND tbl_business.bid LIKE '%%'
AND `tbl_business`.`contperson` LIKE '%%'
AND `tbl_business`.`zonecode` LIKE '%%'
AND `tbl_activities`.`act_code` LIKE '%%'
AND `tbl_business`.`roadstreet` LIKE '%%'
AND `tbl_business`.`company` LIKE '%%'
AND `tbl_business`.`building` LIKE '%%'
ORDER BY `tbl_business`.`appformno` ASC
LIMIT 100 

Omitting the Line:

AND `tbl_activities`.`act_code` LIKE '%%'

Solves the problem Since i know the record doesn't have a related record on the second table, why should i match with LIKE.

 

I will have to have another button for searching such records since on a search that includes AND `tbl_activities`.`act_code` LIKE '%%' will NOT show records without a matching record on the second table(tbl_activities)

OR what do you think:?

Only include the conditions if you actually need them.

// multiple statements
$query = "SELECT ...";
if ($condition) $query .= " AND table.field LIKE '%foo%'";

// one big query
$query = "
    SELECT ...
    " . ($condition ? "AND table.field LIKE '%foo%'" : "") . "

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.