我有三张桌子:
Info:
| article_id | title | author | rating | num_comments |
|------------|----------------|---------------------|------------|--------------|
| 1 | a title | an author | 3.5 | 2 |
| 2 | another title | a different author | 2 | 0 |
Articles:
| article_id | text |
|------------|------------------|
| 1 | longish text... |
| 2 | more text... |
Comments:
|comment_id | article_id | name | comment | date_added |
|-----------|------------|-------------|------------|------------|
| 1 | 1 | this name | first ! | 2013-10-25 |
| 2 | 1 | that name | bla | 2013-10-26 |
我可以从前两个检索数据而不会出现问题:
SELECT Info.*, Articles.text
FROM Info
JOIN Articles
ON Info.article_id = Articles.article_id
WHERE article_id = :article_id
但是现在我想从第三个表中获取匹配的行,按日期对它们进行排序,最好将它们输出到一个多维数组中。 一个查询甚至可以实现这一点吗?
因此,article_id = 1
的预期结果应如下所示:
array {
[article_id] => 1,
[title] => a title,
[author] => an author,
[rating] => 3.5,
[num_comments] => 2,
[text] => longish text...,
[comments] => array {
[1] => array {
[comment_id] => 1,
[name] => this name,
[comment] => first !,
[date_added] => 2013-10-25
[2] => array {
[comment_id] => 2,
[name] => that name,
[comment] => bla,
[date_added] => 2013-10-26
}
}
答案 0 :(得分:2)
即使您没有评论,也可以使用LEFT JOIN来获取文章的结果:
SELECT i.*, a.text, c.*
FROM Info i
INNER JOIN Articles a ON Info.article_id = Articles.article_id
LEFT JOIN Comments c ON c.article_id = a.article_id
WHERE a.artice_id = :article_id
答案 1 :(得分:1)
只需添加另一个连接语句并加入第三个表
答案 2 :(得分:0)
我没有测试过这个
SELECT * FROM Articles
JOIN Info ON Articles.id = Info.article_id
JOIN Comments ON Info.article_id = Comments.article_id WHERE Comments.article_id = :article_id