加入MySQLi以获取多个表数据

时间:2014-02-21 06:25:07

标签: join mysqli

enter image description here

我有两个表用户并且关注。我想编写视图,以便它将获取perticuler用户的所有详细信息以及作为跟随者计数和跟随者别名的两个额外列。

例如。 user id = 11然后来自用户表的所有详细信息加上followcount 1并跟随count1

2 个答案:

答案 0 :(得分:2)

SELECT u.id, 
       u.userid, 
       u.name, 
       u.mobile, 
       (SELECT Count(*) 
        FROM   follow f 
        WHERE  f.followerid = u.userid) AS follower, 
       (SELECT Count(*) 
        FROM   follow f 
        WHERE  f.followeeid = u.userid) AS followee 
FROM   users u 

答案 1 :(得分:0)

您可以通过在查询中使用JOIN语句来实现此目的:

如何实现最终结果的示例:

CREATE VIEW [Followers] AS 
SELECT a.name, a.email, a.mobile, COUNT(SELECT COUNT(followerID) FROM follow WHERE followerID = a.userid), COUNT(SELECT COUNT(followeeID) FROM follow WHERE followeeID = a.userid) FROM users a INNER JOIN follow b ON b.followerID = a.userid