用户可以通过邮政编码(例如:L14,L15,L16)或文本框中的位置进行搜索。改进SQL查询以避免结合的另一种方法?
如果用户输入“利物浦”,它会找到所有位于“利物浦”的商店。如果用户输入邮政编码(例如:L15),它将搜索所有在L15邮政编码区域发货的商店。
请参见下表:
mysql> select * from shops;
+----+----------+-----------+----------+
| id | name | location | postcode |
+----+----------+-----------+----------+
| 1 | Shop One | Liverpool | L10 |
| 2 | Shop Two | Liverpool | L16 |
+----+----------+-----------+----------+
-
mysql> select * from shops_delivery_area;
+------------------+---------+----------+---------------+
| delivery_area_id | shop_id | postcode | delivery_cost |
+------------------+---------+----------+---------------+
| 1 | 1 | L10 | 1.50 |
| 2 | 1 | L11 | 0.00 |
| 3 | 1 | L12 | 1.00 |
| 4 | 1 | L13 | 1.00 |
| 5 | 2 | L10 | 2.50 |
| 6 | 2 | L16 | 0.00 |
| 7 | 2 | L28 | 0.00 |
+------------------+---------+----------+---------------+
SQL查询:
SELECT U.* FROM
((SELECT DISTINCT shops.*, DA.delivery_cost, DA.postcode AS AreaPostcode FROM shops
JOIN shops_delivery_area as DA on (DA.shop_id = shops.id)
WHERE DA.postcode = "Liverpool")
UNION
(SELECT DISTINCT shops.*, DA.delivery_cost, DA.postcode AS AreaPostcode FROM shops
JOIN shops_delivery_area as DA on
(DA.shop_id = shops.id AND
DA.postcode = shops.postcode)
WHERE shops.location = "Liverpool")) as U
-
结果 - 通过位置(利物浦):
+----+----------+-----------+----------+---------------+--------------+
| id | name | location | postcode | delivery_cost | AreaPostcode |
+----+----------+-----------+----------+---------------+--------------+
| 1 | Shop One | Liverpool | L10 | 1.50 | L10 |
| 2 | Shop Two | Liverpool | L16 | 0.00 | L16 |
+----+----------+-----------+----------+---------------+--------------+
结果 - 通过邮编(L12):
+----+----------+-----------+----------+---------------+--------------+
| id | name | location | postcode | delivery_cost | AreaPostcode |
+----+----------+-----------+----------+---------------+--------------+
| 1 | Shop One | Liverpool | L10 | 1.00 | L12 |
+----+----------+-----------+----------+---------------+--------------+
它似乎正常工作... 是提高有其他的方式SQL查询更短,以避免union
什么的?
你对避免'UNION'什么道理呢?附:我认为你可以删除'DISTINCT'关键字,因为'UNION'是'UNION DISTINCT'的缩写。 – onedaywhen 2012-02-10 14:19:38