Consider the SQL query below:
SELECT DISTINCT shops.*,
DA.delivery_cost,
DA.postcode
FROM shops
JOIN shops_delivery_area as DA on DA.shop_id = shops.id
WHERE DA.postcode = "Liverpool"
OR location = "Liverpool"
shops table
+----+----------+-----------+----------+
| id | name | location | postcode |
+----+----------+-----------+----------+
| 1 | Shop One | Liverpool | L10 |
| 2 | Shop Two | Liverpool | L16 |
+----+----------+-----------+----------+
shops_delivery_area table
+------------------+---------+----------+---------------+
| delivery_area_id | shop_id | postcode | delivery_cost |
+------------------+---------+----------+---------------+
| 1 | 1 | L10 | 0.00 |
| 2 | 1 | L11 | 0.00 |
| 3 | 1 | L12 | 1.00 |
| 4 | 1 | L13 | 1.00 |
| 5 | 2 | L10 | 0.00 |
| 6 | 2 | L16 | 0.00 |
| 7 | 2 | L28 | 0.00 |
+------------------+---------+----------+---------------+
User can search by Postcode (eg: L14, L15, L16) or Location from a textbox.
If user type in “Liverpool”, it will find all the shops that are located in “Liverpool”. The problem is there will be duplicate rows of shop name (shops table). How to solve this issue?
Result (Search by Location):
How to avoid duplication of shop name?
I should do: shops.id = shops_delivery_area.shop_id AND shops.postcode = shops_delivery_area.postcode
+----+----------+-----------+----------+---------------+----------+
| id | name | location | postcode | delivery_cost | postcode |
+----+----------+-----------+----------+---------------+----------+
| 1 | Shop One | Liverpool | L10 | 0.00 | L10 |
| 1 | Shop One | Liverpool | L10 | 0.00 | L11 |
| 1 | Shop One | Liverpool | L10 | 1.00 | L12 |
| 1 | Shop One | Liverpool | L10 | 1.00 | L13 |
| 2 | Shop Two | Liverpool | L16 | 0.00 | L10 |
| 2 | Shop Two | Liverpool | L16 | 0.00 | L16 |
| 2 | Shop Two | Liverpool | L16 | 0.00 | L28 |
+----+----------+-----------+----------+---------------+----------+
Result (Search by Postcode L10):
Work fine as expected
+----+----------+-----------+----------+---------------+----------+
| id | name | location | postcode | delivery_cost | postcode |
+----+----------+-----------+----------+---------------+----------+
| 1 | Shop One | Liverpool | L10 | 0.00 | L10 |
| 2 | Shop Two | Liverpool | L16 | 0.00 | L10 |
+----+----------+-----------+----------+---------------+----------+
I have managed to get it working. I have used UNION to solve this problem.
If there anyway to make this code shorter or improve it, let me know. thanks