如何将数组赋值给sql查询的变量

时间:2014-09-30 07:36:45

标签: php mysql sql arrays json

我希望将查询结果(" A")作为数组分配到另一个查询的自定义变量中(" B")。我意识到在sql中不允许使用数组变量,所以我希望在JSON中实现它。   以下是示例:

Query Result A:
Staff ID | Mariage status | Kids Details |
I022144  | yes            |              |
I062541  | yes            |              |
I322411  | yes            |              |
I445211  | no             |              |
D235544  | yes            |              |

Query Result B:
Staff ID | Kids Name      | Kids Gender  | Kids Age  |
I022144  | Pete           | M            | 3          |
I022144  | Sarah          | F            | 5          |
I062541  | Don            | M            | 10         |
I322411  | Keith          | M            | 9          |
D235544  | John           | M            | 2          |
D235544  | Nancy          | F            | 13         |
D235544  | Don            | M            | 1          |

JSON中的预期结果

Dataset: [
  {"Staff ID": I022144, "Mariage status": yes, "Kids Details": [{"Kids Name": Pete, "Kids Gender": M, "Kids Age": 3}, {"Kids Name": Sarah, "Kids Gender": F, "Kids Age": 5}]},
  {"Staff ID": I062541, "Mariage status": yes, "Kids Details": [{"Kids Name": Don, "Kids Gender": M, "Kids Age": 10}]},
  {"Staff ID": I322411, "Mariage status": yes, "Kids Details": [{"Kids Name": Keith, "Kids Gender": M, "Kids Age": 9}]},
  {"Staff ID": I445211, "Mariage status": no, "Kids Details": []},
  {"Staff ID": D235544, "Mariage status": yes, "Kids Details": [{"Kids Name": John, "Kids Gender": M, "Kids Age": 2}, {"Kids Name": Nancy, "Kids Gender": F, "Kids Age": 13}, {"Kids Name": Don, "Kids Gender": M, "Kids Age": 1}]}
]

感谢您的指导。 :)

家伙

1 个答案:

答案 0 :(得分:0)

You actualy can use array variables in SQL, You can do this
DECLARE @TableVariableName TABLE(
IDs VARCHAR(100),
numbers Int
);
Insert into @TableVariableName
 -----Do the select you want it to store it into the new table for example:
Select IDs,numbers from tbl1

然后您可以在另一个查询中使用此表,如下所示:

Select tbl2.column1, @TableVariableName.IDs, @TableVariableName.numbers from tbl2
join @TableVariableName ON tbl2.IDs = @TableVariableName.IDs

你去吧。希望这有帮助