【问题标题】:How to assign an array to a variable of a sql query如何将数组分配给sql查询的变量
【发布时间】:2014-09-30 07:36:45
【问题描述】:

我希望将查询结果(“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}]}
]

感谢您的指导。 :)

开心

【问题讨论】:

  • json_encode? php.net/manual/it/function.json-encode.php 。在 A 上执行查询,将其推送到数组中,使用 json_encode 传递数组,返回的字符串应该是你正在寻找的,如果我有你想做的:P
  • 感谢您的快速回复。我的后续问题是因为将结果 B 分配给结果 A 中的“儿童详细信息”取决于员工 ID。我如何添加一个条件来检查当 A."Staff ID" = B."Staff ID" 然后 A."Kids Details" => {B."Kids Name", B."Kids Gender", B."儿童年龄"} ?
  • 我不确定这是否正是您想要做的。此外,我还没有看到您尝试过的任何代码。我的只是一个想法,但是,如果我有你想做的事情,那么此时你应该很容易完成你需要的事情。但是,如果您想将值存储到数据库中,请注意 json 字符串非常大,因此不要忘记制作一个适当的表以便正确存储它们:)。编辑:另外,很明显,别忘了先转义他们 ;)

标签: php mysql sql arrays json


【解决方案1】:
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

你去。希望这会有所帮助

【讨论】:

  • 谢谢亚历克斯。但是,您的建议似乎会导致表格变平。我只希望“儿童详细信息”列是一个数组。我认为 briosheje 的建议更适合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多