需要一些关于这个PHP代码的帮助

时间:2016-06-16 15:06:51

标签: php mysql

我需要一些帮助来获取每个用户的数据,并且需要从userid获取另一个表文章示例:

我的用户名为(tbl_users)

id=1 username=(admin) name=(Claudio) referer=(admin)
id=2 username=(test) name=(testing) referer=(admin)
id=33 username=(claudia) name=(Claudia) referer=(admin)

我有这篇文章(称为文章)

articleid=5 postedby=(userid=2) title=(articles test1) description=(article test description1) posted(ok)
articleid=6 postedby=(userid=33) title=(articles test2) description=(article test description2) posted(error)
articleid=7 postedby=(userid=2) title=(articles test3) description=(article test description3) posted(error)
articleid=8 postedby=(userid=33) title=(articles test4) description=(article test description4) posted(ok)
articleid=9 postedby=(userid=2) title=(articles test5) description=(article test description5) posted(ok)
articleid=10 postedby=(userid=33) title=(articles test6) description=(article test description6) posted(error)

现在我想得到所有mysql_num_rows由userid发布在表格文章中分开ok = 3 error = 3 and total = 6

示例:

user=test totalarticles=3 postedok=1 postederror=2
user=claudia  totalarticles=3 postedok=2 postederror=1

1 个答案:

答案 0 :(得分:0)

SELECT username, 
  (SELECT COUNT(*) FROM articles a WHERE u.id = a.userid) as totalarticles,
  (SELECT COUNT(*) FROM articles a WHERE u.id = a.userid AND posted = 'ok') as postedok,
  (SELECT COUNT(*) FROM articles a WHERE u.id = a.userid AND posted = 'error') as postederror
FROM tbl_users u 

这应该以resonalbe速度为您提供所需的所有数据。有很多方法可以让数据更加出色,但这是最容易理解的方法。