开发者

How to get 1 row from Table A and multiple rows from Table B

Table A is named "users" and Table B is named "comments". I want to select fields "user_id" and "user_name" from Table A and "date", "comment", "user_id" fields in Table B.

In a nutshell I am trying to get all the use开发者_运维问答rs and their comments with 1 query. Can the comments be put in its own array as there will be multiple comments like below or will it just be 1 comment and would have to run 2 queries?

Basic Example

user_id = 1
username = foo
comments[0]['date'] = 1234567890
comments[0]['comment'] = "Hello World!"
comments[1]['date'] = 1234567890
comments[1]['comment'] = "MySQL n00b"

Any basic examples would be great so I can get my head round it.


This would be a general query, to select all the comments of user_id = 1.

SELECT u.user_id, u.user_name, c.`date`, c.`comment`
FROM comments c
INNER JOIN users u ON c.user_id = u.user_id
WHERE c.user_id = 1


Assuming the user_id is 1, here is the code if you want an associative array with all user's comments. There is only one query, using JOIN statement.

$res = mysql_query("SELECT users.user_id as uid, users.user_name as username, comments.date, comments.comment, comments.user_id as cid FROM `users` LEFT JOIN comments on uid=cid WHERE cid = 1");

$i = 0;
while($arr = mysql_fetch_assoc($res))
{
     $comments[$i]['date'] = $arr['date'];
     $comments[$i]['comment'] = $arr['comment'];
     $i++;
}

//var_dump($comments);


We call this JOIN. Better to take some sql/mysql tutorial or you get lost.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜