这是我的数据库表,如何查询,以便我可以获得所需的输出,如下所示。我可以使用单个查询语句查询数据库以获取json输出???
Table name: rowManager
+-------------+-----------------+----------------+
| rowid | rowname | showid |
+-------------+-----------------+----------------+
| 1 | first | 0 |
| 17 | second | 2 |
| 18 | third | 0 |
| 20 | forth | 0 |
+-------------+-----------------+----------------+
Table name: row_vid
+-------------+----------------+-----------------+-----------------+
| rowid | name | description | submission_date |
+-------------+----------------+-----------------+-----------------+
| 1 | Learn PHP | abavavaav | 2007-05-24 |
| 17 | Learn MySQL | sdasdsa | 2007-05-24 |
| 20 | JAVA Script | Sanjay | 2007-05-06 |
| 1 | JAVA | Sanjay | 2007-05-06 |
| 18 | Android | Sanjay | 2007-05-06 |
| 17 | ios | Sanjay | 2007-05-06 |
| 1 | python | Sanjay | 2007-05-06 |
| 18 | c++ | Sanjay | 2007-05-06 |
| 18 | c# | Sanjay | 2007-05-06 |
| 17 | ruby | Sanjay | 2007-05-06 |
| 18 | JQuery | Sanjay | 2007-05-06 |
| 17 | objective c | Sanjay | 2007-05-06 |
| 1 | JAVA Tutorial | Sanjay | 2007-05-06 |
+-------------+----------------+-----------------+-----------------+
$rowQuery='SELECT * from row_vid,rowManagr where rowManagr.showid=0';
我正在尝试查询这些表,以便它输出如下:
{
"responses":{
"First":[
{
"name":"Learn PHP"
},
{
"name":"JAVA"
},
{
"name":"python"
},
{
"name":"JAVA Tutorial"
}
],
"Other Show":[
{
"name":"Learn MySQL"
},
{
"name":"ios"
},
{
"name":"ruby",
},
{
"name":"objective c"
}
],
"Videos":[
{
"name":"Android"
},
{
"name":"c++ "
},
{
"name":"c#",
},
{
"name":"JQuery"
}
]
}
}
由于
答案 0 :(得分:3)
首先,我相信这是您正在寻找的查询:
SELECT rowManager.rowname as category, row_vid.name as name
FROM rowManager, row_vid
WHERE rowManager.rowid=row_vid.rowid
ORDER BY rowManager.rowid, row_vid.name
在PHP中,您可以这样做:
$sql = "SELECT rowManager.rowname as category, row_vid.name as name FROM rowManager, row_vid WHERE rowManager.rowid=row_vid.rowid ORDER BY rowManager.rowid, row_vid.name"
$query_result = mysqli_query($sql);
// Piece together the $responses array, which will have [category]
// as key, while value is an array of 'name':[name]' pairs.
$responses = array();
while ($row = mysqli_fetch_assoc($query_result)) {
if (!array_key_exists($row['category'], $responses)) {
$responses[$row['category']] = array();
}
array_push($responses[$row['category']], array('name' => $row['name']));
}
// Entire $response array is the value of 'responses' key in the
// final $results array.
$results = array('responses' => $responses);
// Convert $results_array to JSON and print.
print(json_encode($results));
答案 1 :(得分:1)
您可能希望使用JOIN来构建您收集的数据。但是,你必须手动"把我变成JSON
。 mysql
没有内置函数来返回JSON
数据。您可以使用php
中的回复执行此操作,也可以使用CONCAT或类似内容在mysql中构建JSON
响应。
您最好能够调试,跟踪错误并轻松处理JSON
布局,可以通过迭代php
结果并构建多维来mysql
执行此操作array
具有相似的布局,然后在阵列上运行json_encode。
答案 2 :(得分:0)
如果rowManager和row_vid之间的关系与列名rowid有关,那么你不能得到这些查询的输出 -
SELECT
*
FROM
row_vid AS rvid
LEFT JOIN
rowManagr rm ON rvid.rowid = rm.rowid
WHERE
rm.showid = 0
在此查询之后,您将不得不使用php迭代此查询结果并格式化您的预期数据并使用php将此数据编码为json。