带有连接或子查询的MySQL查询

时间:2012-09-12 19:21:17

标签: mysql sql database

我有这样的架构和查询: 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;

通过比较两个表的userid列,我需要加入它们 我需要一个具有这些列的输出:
times, userid, name, age, location
还应考虑订单,组和限制。

如果你能用JOIN写一个查询,用子查询写一个查询,我会很高兴 我有一张60k的桌子,我将比较它们的表现。

1 个答案:

答案 0 :(得分: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 with demo