简体   繁体   中英

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

I am new to mysql so you will have to bare with me.

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 users 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.

Thanks

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM