drxpt06820 2010-08-13 18:58
浏览 76
已采纳

使用可选参数/排名构造SQL查询

I was wondering what would be a good way to accomplish the following using mysql:

Lets say I have a table that contains these fields:

MyTable
---------
Country [string]
Region/Province/State [string]
City [string]

And I have the following data rows in the database

Entry 1: Canada, Ontario, Toronto
Entry 2: Canada, Ontario, Hamilton
Entry 3: Canada, Alberta, Calgary

Now I want to be able to search that table based on user supplied information, However, if there are no results found with the user's supplied information I want the program to try and make it less specific. For example, if the user supplies:

Canada, Ontario, Kingston

I would like the search query to search for all 3 fields (which would produce 0 rows), then just for the country/region (which would produce 2 rows), and then just for the country (which should produce only 1 extra row on top of the previous two). Is that possible and, if it is, would it be fairly efficient ? Can this be done with 1 query or would it require multiple queries and then some cross-referencing to eliminate identical rows (I imagine that wouldn't be very efficient) ?

Thank you very much!

Edit By cross-referencing/multiple queries I was thinking about using UNION with several selects. But I was wondering if there is a better/more logical way to do this.

  • 写回答

2条回答 默认 最新

  • duangan1945 2010-08-13 19:04
    关注

    I would go with the 3 queries.

    Normalize the table so you can check on small tables for country, region/province/state and city and then link them to the actual entries on a 1 -> N (one to many relationship).

    SELECT * FROM cities
    LEFT JOIN actual_locations ON actual_locations.city = cities.id 
    WHERE cities = 'NYC'
    

    Hope it helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?