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 

Link to comment
Share on other sites

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:?

Link to comment
Share on other sites

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%'" : "") . "

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.