See the SQL Query below, it seem to be working well. It allow me to search the record via postcode or town.
User type in the postcode or town from a textbox.
There is a list of Postcodes (BB1, BB2, BB3, etc) from uk_postcodes table.
If user type in BB2 or BB2 XXX, it will then display a list of shop record that do delivery in the BB2 area. (I use PHP to get the first part of the postcode before it goes into SQL query)
If User type in Blackburn then it will display list of shops with default delivery area (D.shop_id = S.shop_id AND D.postcode_id = S.postcode_id)
$SQL = "(SELECT DISTINCT S.*, D.delivery_cost, D.postcode AS DeliveryAreaPostcode FROM shops AS S
JOIN shop_delivery_area AS D ON D.shop_id = S.shop_id
JOIN uk_postcodes AS P ON P.postcode_id = D.postcode_id
WHERE P.postcode = '$search' ORDER BY D.postcode)
UNION
(SELECT DISTINCT S.* , D.delivery_cost, D.postcode AS DeliveryAreaPostcode FROM shops AS S
JOIN shop_delivery_area AS D ON D.shop_id = S.shop_id AND D.postcode_id = S.postcode_id
JOIN uk_postcodes AS P ON P.postcode_id = D.postcode_id
WHERE S.town = '$search')";
Is this SQL query good? or what can be improved or make it smaller?
Using UNION ALL is quicker than using UNION since a distinct check does not need to be done.
In this instance, unless someone lives in a town that’s also a postcode you do not need that overhead!