2

我有这样的架构和查询: http ://sqlfiddle.com/#!2/7b032/3

另外我有这些查询:

SELECT COUNT(*) AS 'times', userid, name
FROM main
WHERE comedate <= DATE_SUB(CURDATE(),
                   INTERVAL 5 DAY)
GROUP BY userid ORDER BY times DESC LIMIT 0,2;

SELECT * FROM details WHERE 1;

通过比较两个表的用户 ID 列,我需要加入它们。
我需要具有以下列的输出:
times, userid, name, age, location
还应考虑顺序、组和限制。

如果您可以编写一个带有 JOIN 的查询和一个带有子查询的查询,我会很高兴。
我有一张 60k 的桌子,我会比较性能。

4

1 回答 1

1

这个怎么样:

select x.times,
  x.userid,
  x.name,
  d.age,
  d.location
from 
(
  SELECT COUNT(*) AS 'times', userid, name
  FROM main
  WHERE comedate <= DATE_SUB(CURDATE(),
                     INTERVAL 5 DAY)
  GROUP BY userid 
) x
left join details d
  on x.userid = d.userid

SQL Fiddle with Demo

编辑:

select x.times,
  x.userid,
  x.name,
  d.age,
  d.location
from 
(
  SELECT COUNT(*) AS 'times', userid, name
  FROM main
  WHERE comedate <= DATE_SUB(CURDATE(),
                     INTERVAL 5 DAY)
  GROUP BY userid
  ORDER BY times DESC 
  LIMIT 0,2
) x
left join details d
  on x.userid = d.userid

请参阅带有演示的 SQL Fiddle

于 2012-09-12T19:26:31.460 回答