请参阅下面的SQL查询,它似乎运行良好。它允许我通过邮政编码或城镇搜索记录。
用户在文本框中输入邮政编码或城镇。
uk_postcodes
表中有一个邮政编码列表(BB1,BB2,BB3等)。
如果用户输入BB2或BB2 XXX,则会显示在BB2区域内发送的商店记录列表。 (在进入SQL查询之前,我使用PHP获取邮政编码的第一部分)
如果用户输入Blackburn
,则会显示具有默认投放区域的商店列表(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')";
这个SQL查询好吗?或者可以改进什么或使其变小?
答案 0 :(得分:1)
你可以使用一个控制变量,一些是
$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确定当前用户选择
格式是这里的虚拟函数代码
// 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;
}
答案 1 :(得分:1)
使用UNION ALL比使用UNION更快,因为不需要进行明确的检查。 在这种情况下,除非有人住在一个也是邮政编码的城镇,否则你不需要这笔费用!