MySQL从同一个表中连接多个列

时间:2010-09-17 20:44:12

标签: mysql join multiple-columns

我正在尝试编写一个查询,该查询返回用户配置文件信息,以及另一个表中2列中用户ID的出现次数。以下示例:

TableA
userID  userName
1       UserA
2       UserB

TableB
LinkID  leadID  followID
1       1       2
2       1       3
3       2       1

查询UserID 1我希望检索 UserA 2 (在leadID中出现1), 1 (出现1)在followID)。非常感谢任何帮助,并提前感谢。

3 个答案:

答案 0 :(得分:3)

你实际上并不需要为此加入 - 你可以改为三次单独选择。

SELECT
(
    SELECT userName
    FROM TableA
    WHERE userID = 1
) AS userName,
(
    SELECT COUNT(*)
    FROM TableB
    WHERE leadID = 1
) AS count_leadID,
(
    SELECT COUNT(*)
    FROM TableB
    WHERE followID = 1
) AS count_followID

结果:

userName  count_leadID  count_followID
UserA     2             1             

答案 1 :(得分:0)

SELECT a.userName,
       SUM(IF(b.leadId = a.userId, 1, 0) as Leads,
       SUM(IF(b.followId = a.userId, 1, 0) as Follows
FROM TableA a
     TableB b
GROUP BY a.userName

答案 2 :(得分:0)

SELECT a.userName,
       b1.count(*) as leads,
       b2.count(*) as follows
FROM TableA a
INNER JOIN TableB b1 on a.userID = b1.leadID
INNER JOIN TableB b2 on a.userID = b2.followID
GROUP BY a.userName

取决于mySQL如何优化,如果你有关于leadID和followID的索引,那么这可以加快查询速度,特别是如果你只是同时查询几个用户而不是全部用户。