Another way to improve the SQL Query to avoid union?

后端 未结 4 1134
南方客
南方客 2021-01-18 00:23

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

相关标签:
4条回答
  • 2021-01-18 00:33

    Since all tables and selected columns are the same, you can simply do this:

      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")
          OR (DA.postcode = shops.postcode AND shops.location = "Liverpool")
    

    Like you said in Diego's answer, the conditions are a litle different! So, you compensate that difference in the WHERE clause.

    0 讨论(0)
  • 2021-01-18 00:44

    What am I missing? Why cant you do

     WHERE DA.postcode = "Liverpool" or shops.location = "Liverpool"
    
    0 讨论(0)
  • 2021-01-18 00:53

    please try this:

    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" and DA.postcode = shops.postcode)
    
    0 讨论(0)
  • 2021-01-18 00:54

    Whatever you choose, be aware that short code is not always optimal code. In many cases, where you have sufficiently divergent logic, unioning the results really is the most optimal (and sometimes most clean, programatically) option.

    That said, the following OR in the WHERE clause seems to cover both your cases...

    SELECT DISTINCT
      shops.*,
      DA.delivery_cost,
      DA.postcode AS AreaPostcode
    FROM
      shops
    INNER JOIN
      shops_delivery_area as DA
        ON (DA.shop_id = shops.id)
    WHERE
      (DA.postcode = "Liverpool")
    OR
      (DA.postcode = shops.postcode AND shops.location = "Liverpool")
    
    0 讨论(0)
提交回复
热议问题