MySQL子查询使用相同的表

时间:2015-03-26 18:35:22

标签: mysql subquery

我正在尝试使用列==列的子查询从同一个表中检索一些ID。

SELECT 
`assemblies`.`id`,
`assemblies`.`type`,
`assemblies`.`champion`,
`assemblies`.`name`,
`assemblies`.`author`,
`assemblies`.`githubLastmod`,
(assemblies.forum IS NOT NULL) AS forumExists,
(SELECT GROUP_CONCAT(`champion`) FROM `assemblies` WHERE `githubFolder` = `githubFolder`) AS champions,
(SELECT COUNT(*) FROM `votes` WHERE `assembly` = `assemblies`.`id`) AS votesCount,
(SELECT COUNT(*) FROM `install_clicks` WHERE `assembly` = `assemblies`.`id`) AS installCount,
(SELECT COUNT(*) FROM `github_clicks` WHERE `assembly` = `assemblies`.`id`) AS githubCount,
(SELECT COUNT(*) FROM `forum_clicks` WHERE `assembly` = `assemblies`.`id`) AS forumCount,
(SELECT COUNT(*) FROM `broken_assemblies` WHERE `assembly` = `assemblies`.`id` AND `ip` = '192.168.10.1') AS isBroken,
(SELECT COUNT(*) FROM `votes` WHERE `assembly` = `assemblies`.`id` AND `ip` = '192.168.10.1') AS isUpvoted
FROM
`assemblies`
WHERE
`assemblies`.`type` = 'champion'
    AND `assemblies`.`champion` = '84'
    AND UNIX_TIMESTAMP(DATE(assemblies.githubLastmod)) > '1419617372'
ORDER BY `votesCount` DESC , `githubLastmod` DESC

这部分:

(SELECT GROUP_CONCAT(`champion`) FROM `assemblies` WHERE `githubFolder` = `githubFolder`) AS champions,

这将从所有行返回champion,如果githubAddress匹配,我只想要champion

(我尽力解释这个,哈哈,如果你需要更多信息,请发表评论)

1 个答案:

答案 0 :(得分:0)

我们需要GROUP BY githubFolder而不是WHERE githubFolder = githubFolder

如果我们单独执行此操作,它将完全符合我们想要实现的目标

(SELECT GROUP_CONCAT('champion') FROM assemblies GROUP BY githubFolder) AS champions

但如果这将作为子查询执行,它将返回错误,因为它返回多行