我有两张桌子:
authors
+-----------+--------------+------+-----+
| Field | Type | Null | Key |
+-----------+--------------+------+-----+
| id | int(6) | NO | PRI |
| name | varchar(255) | NO | |
| age | varchar(255) | NO | |
+-----------+--------------+------+-----+
books
+-----------+--------------+------+-----+
| Field | Type | Null | Key |
+-----------+--------------+------+-----+
| id | int(6) | NO | PRI |
| name | varchar(255) | NO | |
| pub_date | datetime | NO | |
| author_id | int(11) | YES | MUL |
+-----------+--------------+------+-----+
我想通过他最后的书面信息获取作者信息。 看起来像这样的东西:
{
name:"Tolkien",
age:null,
last_book:{
name:"The Children of Hurin",
pub_date:"2007"
}
}
现在我这样做:
Select Aut.name, Aut.age, Book.name AS Book_name, Book.pub_date
FROM authors AS Aut
LEFT JOIN books AS Book ON (Aut.id=Book.author_id)
WHERE Aut.name="Tolkien"
ORDER BY Book.pub_date DESC
LIMIT 1
这意味着我必须处理结果,然后命令它拥有我之前显示的json。
答案 0 :(得分:0)
唯一的方法是进行后处理,但如果使用json_encode
来序列化对象则不是这样:
$res = mysqli_query("SELECT ...");
$obj = new stdClass();
if($row = mysqli_fetch_object($res)) {
$obj->name=$row->name;
$obj->age=$row->age;
$book = new stdClass();
$book->name = $row->Book_name;
$book->pub_date = $row->pub_date;
$obj->last_book = $book;
}
print json_encode($obj);