简体   繁体   中英

How to improve SQL query

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?

You can use one control variable, some how

$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 = '{0}' and '{1}' = 'postcode' )
         or (S.town = '{0}' and D.postcode_id = S.postcode_id and '{1}' = 'town' )
            ORDER BY D.postcode".format($search, $myflagcontrol);

$myflagcontrol is determinate for current user selection

Format is a dummy function here code

// Add format extension to string class
String.prototype.format= function(){    
var str = this;
for (var i = 0, l = arguments.length; i < l; i++)   
    str = str.replace("{" + i + "}", arguments[i]); 
return str;
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM