我目前有一个MySQL表格,如:
id | friend
1 | 2
1 | 5
1 | 10
3 | 6
15 | 19
21 | 4
我正在尝试获取某个特定用户的所有朋友ID,并将它们排列成逗号分隔的列表。例如,抓住user1的朋友,它将返回
$friend_list = 2,5,10
目前,我有:
$sql = "SELECT friend FROM table__friends WHERE id = ".$user_id;
这只抓了一排..请帮助!
由于
答案 0 :(得分:12)
您想使用GROUP_CONCAT:
$sql = "SELECT GROUP_CONCAT(friend) FROM table__friends GROUP BY id HAVING id = ".$user_id;
根据更好的答案调整正确性。
答案 1 :(得分:4)
$sql = "SELECT GROUP_CONCAT (DISTINCT friend SEPARATOR ',')
FROM table_friends GROUP BY id
HAVING id =".$user_id;
答案 2 :(得分:1)
您的查询将返回多行 - 听起来您只是在阅读第一行。你需要这样的东西:
$sql = "SELECT friend FROM table__friends WHERE id = "
. mysql_real_escape_string($user_id);
$result = mysql_query($sql);
if (!$result) {
die("Something bad happened");
}
$friend_arr = array();
while ($row = mysql_fetch_array($result)) {
$friend_arr[] = $row[0];
}
$friend_list = implode(',', $friend_arr);
发布您用于运行查询的PHP代码,我们将能够提供更多帮助。
几点说明:
mysql_real_escape_string
功能。以这种方式清理用户输入 至关重要 以避免SQL injection攻击。答案 3 :(得分:0)
答案 4 :(得分:0)
我使用了一个名为@a的变量来存储id,最后你有变量中的值或者尝试 有限制,组顺序,如下:
mysql> show create table actor\G
*************************** 1. row ***************************
Table: actor
Create Table: CREATE TABLE `actor` (
`actor_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`actor_id`),
KEY `idx_actor_last_name` (`last_name`)
) ENGINE=InnoDB AUTO_INCREMENT=207 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
mysql> set @a:=0;
Query OK, 0 rows affected (0.00 sec)
mysql> select @a:=concat(@a,",",actor_id) as actor_id from actor where actor_id>195 order by (actor_id) desc limit 1;
+----------------------------+
| actor_id |
+----------------------------+
| 0,196,197,198,199,200,205, |
+----------------------------+
1 row in set (0.00 sec)
在您的情况下,更改“WHERE条件”
或者您也可以在选择之后:
mysql> select @a;
+-------------------------------+
| @a |
+-------------------------------+
| 0,196,197,198,199,200,205,206 |
+-------------------------------+
1 row in set (0.00 sec)