dou31797719 2013-05-13 15:27
浏览 43
已采纳

SQL Cartesian选择框

I have a PHP form that uses several select boxes that are populated by lookup tables. In an effort to reduce the number of queries per page, I'm trying to find a way to create a cartesian product that would output the results like:

-----------------------------------------------------------------
|        City       |   State    |    SchoolDistrict            |
-----------------------------------------------------------------
| Adamsville        |     AL     |   Adamsville  Public Schools |
| Brownsville       |     AK     |   Baker-Cow USD              |
| Cowtown           |     AR     |   NULL                       |
| NULL              |     AZ     |   NULL                       |
| NULL              |     CA     |   NULL                       |
-----------------------------------------------------------------

Then I could just loop through each field until it found null (or 0-length string).

When I tried:

SELECT a.City, b.State, c.SchoolDistrict FROM Cities a, State b, SchoolDistricts c

it returns:

-----------------------------------------------------------------
|        City       |   State    |    SchoolDistrict            |
-----------------------------------------------------------------
| Adamsville        |     AL     |   Adamsville  Public Schools |
| Brownsville       |     AK     |   Baker-Cow USD              |
| Cowtown           |     AR     |   Baker-Cow USD              |
| Cowtown           |     AZ     |   Baker-Cow USD              |
| Cowtown           |     CA     |   Baker-Cow USD              |
-----------------------------------------------------------------

Any ideas?

  • 写回答

1条回答 默认 最新

  • douyongwan5946 2013-05-13 16:53
    关注

    One solution that I have come up with is

    SELECT a.City, "City" type from Cities a 
    UNION ALL
    SELECT b.State, "State" from States b 
    UNION ALL
    SELECT c.SchoolDistrict, "SchoolDistrict" from SchoolDistricts c 
    

    This would be one query and you can check the value of the second column and do necessary operations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入