[英]Join 2 tables with same field names
I have 2 tables : 我有2张桌子:
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 |
+-----------+--------------+------+-----+
I'd like to get the author information with his last written book information. 我想获得作者信息以及他最近的书面著作信息。 Something that would look like that :
看起来像这样的东西:
{
name:"Tolkien",
age:null,
last_book:{
name:"The Children of Hurin",
pub_date:"2007"
}
}
For now I am doing it that way : 现在,我正在这样做:
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
This means that I have to process the result and then order it to have the json that I showed previously. 这意味着我必须处理结果,然后将其排序为具有我先前显示的json。
Only way is post-processing, but is not so much if you use json_encode
for serializing an object: 唯一的方法是后处理,但是如果您使用
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.