SQL Cartesian选择框

时间:2013-05-13 15:27:51

标签: php mysql

我有一个PHP表单,它使用了几个由查找表填充的选择框。为了减少每页查询的数量,我试图找到一种方法来创建一个输出结果的笛卡尔积,如:

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

然后我可以遍历每个字段,直到找到null(或0长度字符串)。

当我尝试时:

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

它返回:

-----------------------------------------------------------------
|        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              |
-----------------------------------------------------------------

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我提出的一个解决方案是

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 

这将是一个查询,您可以检查第二列的值并执行必要的操作。