查询连接表的SQL

时间:2013-11-21 09:51:43

标签: php sql left-join

我有一个第一个看起来像这样的SQL表:

Table **news**
+----+---------------+
| id | title         |
+----+---------------+
|  1 | My First News |
|  2 | Another News  |
+----+---------------+

和第二张表:

Table **comments**
+----+---------+-----------------------------+
| id | id_news | content                     |
+----+---------+-----------------------------+
|  1 |       1 | lorem ipsum                 |
|  2 |       1 | dolor sit amet              |
|  3 |       2 | consectetur adipiscing elit |
+----+---------+-----------------------------+

现在,当我进入新页面时,我想请求数据库获取这样的数组:

news = {
    'id_news'  => 1
    'title' => 'My First News'
    'comments'  => ['lorem ipsum', 'dolor sit amet']
}

诀窍是用注释创建一个数组。

我不知道是否可以使用一个查询(左连接,...)。

3 个答案:

答案 0 :(得分:1)

关于news.Id = comments.id_news的左连接(新 - >评论)会这样做。 Groupconcat comments.content然后分组on news.Id

对此的MySql查询类似于:

Select id_news,n.title, Group_concat(c.content) from news n left join comments c on n.Id=c.id_news group by n.Id

答案 1 :(得分:0)

一个简单的连接可以解决这个问题:

SELECT
    c.id_news
    , n.title
    , c.content AS comments
FROM
    news n
JOIN 
    comments c
ON
    n.id = c.id_news
WHERE
    n.id = 1;

答案 2 :(得分:0)

<?php

$db = db_connection;
$results = $db->query('SELECT id_news, title, content 
FROM news n LEFT JOIN comments c ON n.id = c.news_id');

$news = array();
while($row = $results->fetch_assoc()){
    $news['id_news']['id_news'] = $row['id_news']; // Here lakmal, you have the id now
    $news['id_news']['title'] = $row['title'];
    $news['id_news']['comments'][] = $row['content'];
}

print_r($news);

输出

news => Array (

    [1] => Array (
        'title' => 'My First News'
        'comments'  => ['lorem ipsum', 'dolor sit amet']
    )

    [2] => Array (
        'title' => 'Another News '
        'comments'  => ['consectetur adipiscing elit']
    )

)