获取包含另一个表中的一些数据的列表用户
我有表(用户) 我还有另一个表(书籍)
用户表:
Id |用户名
1 :: john
2 :: doe
books 表:
id |书名 | user_id(拥有这本书的用户)
1 :: book1 :: 2
2 :: book2 :: 2
3 :: book3 :: 2
4 :: book4 :: 1
5 :: book5 :: 1
现在,我如何获取列表用户数量并获取每个用户拥有多少本书,
如下所示:
john(2 本书)
doe(3 本书)
我使用 codeigniter 框架..
提前致谢:)
I have table ( users )
and I have another table let's say (books)
users table :
Id | Username
1 :: john
2 :: doe
books table:
id | book_title | user_id(user who own this book)
1 :: book1 :: 2
2 :: book2 :: 2
3 :: book3 :: 2
4 :: book4 :: 1
5 :: book5 :: 1
Now , how can I get list of users and get how many books every user have
like this :
john ( 2 books )
doe ( 3 books )
I use codeigniter framework ..
thanks in advance :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
回答你的第二个问题:
我只需要为我自己的一些分析执行此操作:
如果您必须经常执行此操作,您可能想弄清楚如何使用比子查询更有效的多个连接来执行此操作。
To answer your second question:
I just had to do this for some of my own analytics:
If you have to do this frequently, you might want to figure out how to do this using multiple joins which are more efficient than subqueries.
这是SQL数据库吗?你不能使用 SQL 查询来得到你想要的吗?:
Is this SQL database? Couldn't you use SQL query to get what you want?:
在循环访问用户的输出时,您需要使用
$this->db->count_all_results();
和在循环内再次调用数据库其中
行选择用户ID。抱歉没有解释清楚,但如果你理解它的逻辑,那就没问题了。但这是我的解释,没有太多关于
JOIN
的知识,如上所示。While looping through your output of users, you'll want to make another call to the DB within the loop with something like
$this->db->count_all_results();
with awhere
line to select the userID. Sorry for not explaining too well, but if you understand the logic of it, you'll be fine.BUT this is my explanation without too much knowledge of
JOIN
, as seen above.如果你使用 CI 的 Active Record 框架,它会是这样的:
If you're using CI's Active Record framework, it would be something like this: