我正在尝试创建一个包含来自多个表的可选聚合值并且有一些困难的单个查询。我将尝试将问题简化为尽可能少的字段。
表格
应用
appid | pageid
竞赛
id | appid | winnerid
注册等
id | contestid | firstname | lastname
介
id | signupid
票
id | signupid
查询目的
我正在尝试根据 pageid 参数组合应用程序和竞赛表,加入注册表以获取可用的获胜者,然后计算所有注册,推荐和票证或者当没有可用时只是零值。
到目前为止我已经得到了什么
SELECT t1.*, `Winner`.Name AS Winner, IFNULL(`srt`.Signups,0) AS Signups,
IFNULL(`srt`.Referrals,0) AS Referrals,
IFNULL(`srt`.Tickets,0) AS Tickets
FROM applications a, (contests c LEFT JOIN
/* Join signups table to retrieve winner's first/last name */
(SELECT id, contestid, CONCAT(firstname, ' ' , lastname) AS Name
FROM signups) `Winner`
ON c.winnerid = `Winner`.id
AND c.contestid = `Winner`.contestid) LEFT JOIN
/* Join signups, referrals, and tickets to retrieve counts */
(SELECT s.signupid, COUNT(*) AS Signups, Referrals, Tickets
FROM (signups s LEFT JOIN
(SELECT r.signupid, COUNT(r.id) AS Referrals
FROM signups s, referrals r
WHERE s.signupid = r.signupid) `Referrals`
ON s.signupid = `Referrals`.signupid) LEFT JOIN
(SELECT t.signupid, COUNT(t.id) AS Tickets
FROM signups s, tickets t
WHERE s.signupid = t.signupid) `Tickets`
ON s.signupid = `Tickets`.signupid) `srt`
ON signupid = `srt`.signupid
WHERE a.id = c.applicationid
AND a.pageid = @pageid
ORDER BY c.id IN (SELECT id FROM contests WHERE active = 1) desc, c.addeddate desc;
问题
我很肯定这不是最有效的方式来做我想做的事情,不管它不起作用。 signups / referrals / ticket的值只返回每个表中每条记录的计数。获胜者加入工作正常,如果我将其限制为仅注册,那也是有效的。注册表链接到竞赛表,然后引荐和票证直接与注册表相关联。非常感谢您对此复杂查询的任何帮助。
答案 0 :(得分:1)
请原谅我,如果我是误解,也是因为我对MSSQL和mysql之间的差异缺乏了解,但我会尝试这样的事情:
SELECT
( SELECT CONCAT(IFNULL(firstname,''), ' ' , IFNULL(lastname,''))
FROM Signups
WHERE id = c.winnerid) as Winner,
( SELECT COUNT(*)
FROM Signups
WHERE contestid = c.id) as Signups,
( SELECT COUNT(*)
FROM referrals r LEFT JOIN signups su ON r.signupid = su.id
WHERE su.contestid = c.id) as Referrals,
( SELECT COUNT(*)
FROM tickets t LEFT JOIN signups su ON t.signupid = su.id
WHERE su.contestid = c.id) as Tickets
FROM
Contests c