Quantcast
Viewing all articles
Browse latest Browse all 8068

Search database across two tables (LEFT JOIN)

Hi,

I have a customer table, defined like this:

exports.definition = {
    config: {
        "columns": {
            "CustomerId":"INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE",
            "WebsiteId":"INTEGER",
            "GroupId":"INTEGER",
            "DefaultBillingId":"INTEGER",
            "DefaultShippingId":"INTEGER",
            "Email":"TEXT",
            "Firstname":"TEXT",
            "Lastname":"TEXT",
            "Company":"TEXT",
            "Gender":"TEXT",
            "CreatedAt":"TEXT",
            "UpatedAt":"TEXT"
        },
        "adapter": {
            "type":"sql",
            "collection_name":"customers",
            "db_name":"myDB",
            "idAttribute":"CustomerId"
        }
    }
};
Each customer can have one or more (one-to-many) addresses, so they are stored in a table defined like this:
exports.definition = {
    config: {
        "columns": {
            "CustomerAddressId":"INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE",
            "WebsiteId":"INTEGER",
            "WebsiteCustomerId":"INTEGER",
            "FullName":"TEXT",
            "Company":"TEXT",
            "AddressLine1":"TEXT",
            "AddressLine2":"TEXT",
            "Region":"TEXT",
            "City":"TEXT",
            "Postcode":"TEXT",
            "Country":"TEXT",
            "Telephone":"TEXT",
            "CreatedAt":"TEXT",
            "UpatedAt":"TEXT"
        },
        "adapter": {
            "type":"sql",
            "collection_name":"customer_addresses",
            "db_name":"myDB",
            "idAttribute":"CustomerAddressId"
        }
    }
};
So, when I do my search, I use the following query:
var searchResults = db.execute(
    "SELECT c.CustomerId, c.Firstname, c.Lastname, c.Company FROM customers AS c "+
    "LEFT JOIN customer_addresses AS ca ON c.WebsiteId = ca.WebsiteCustomerId "+
    "WHERE ("+
    "c.Firstname LIKE '%"+ searchTerm +"%' OR "+
    "c.Lastname LIKE '%"+ searchTerm +"%' OR "+
    "c.Company LIKE '%"+ searchTerm +"%' OR "+
    "ca.Postcode LIKE '%"+ searchTerm +"%'"+
    ")"
);
Where....

"WebsiteId" in each table refers to a unique ID assigned by our website. This will match for a customer record and a address record(s).

With the above, I am able to find customers by Firstname, Lastname or Company fields. However, I am unable to find any customer by searching postcode.

Any idea why this might be? Is cross table search not supported or something?

P.S. I've already "peaked" at the data held in my db using SQLite browser and the records are there.


Viewing all articles
Browse latest Browse all 8068

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>