我的代码到目前为止: http://sqlfiddle.com/#!2/c421c/6
我想在同一行显示所有电影
期望的输出:
| Name| Favourite movies |
----------------------------
| Alice | Movie A Movie B |
| Bob | Movie A Movie C |
| Carol | (null) |
| Dave | (null) |
我正在使用CodeIgniter 2活动记录
PHP输出
Array
(
[0] => stdClass Object
(
[user] => Test
[gender] => 0
[GROUP_CONCAT(movies.movie SEPARATOR "-")] => Movie A-Movie B
)
我应如何像[user]那样打印最后一个字段的输出(echo $ user-> user;)?
答案 0 :(得分:1)
使用GROUP_CONCAT
GROUP_CONCAT(`movies`.`movie`) AS "Favourite movies"
您也可以更改分隔符,
GROUP_CONCAT(`movies`.`movie` SEPARATOR ' ')
答案 1 :(得分:1)
SELECT `users`.`user` AS name,
group_concat(`movies`.`movie`) AS favorites
FROM (`users`)
LEFT JOIN `users_movies`
ON `users`.`id` = `users_movies`.`user_id`
LEFT JOIN `movies`
ON `users_movies`.`movie_id` = `movies`.`id`
GROUP BY `users`.`user`