从数据库计算平均年龄,合并2个查询

时间:2012-07-23 07:29:24

标签: php mysql

好的,所以我认为这个问题并不像标题所暗示的那么简单但是这里...... 我有这个问题:

SELECT age.*, job.id FROM age, job WHERE ((age.aid = job.id) AND (age.aid='$id'))

这基本上连接两个表age和job并获得匹配的行

但现在我需要在表格年龄

下找到存储在行猜测中的最常见年龄

数据库布局

表:年龄

行:援助 - 猜测

表:工作

行: id

从我发现的搜索中我需要使用count()

例如:

SELECT guess, COUNT(guess) AS countguess FROM age GROUP BY guess ORDER BY countguess DESC LIMIT 1

但是如何将2个查询合并在一起?

4 个答案:

答案 0 :(得分:1)

你可以做这样的事情

SELECT age.aid, job.id, age.guess, COUNT(age.guess) AS countguess 
FROM age, job 
WHERE ((age.aid = job.id) AND (age.aid='$id')) 
GROUP BY guess 
ORDER BY countguess DESC

答案 1 :(得分:0)

当你说合并时,我认为你的意思是加入他们。当两个表之间存在关系时,您可以加入。

答案 2 :(得分:0)

您可以使用UNION ALL来完成此操作

SELECT aid, id, guess, SUM(countguess ) AS countguess
FROM
(
 SELECT age.aid, job.id, guess, 0 AS countguess  
 FROM age
      INNER JOIN job
          ON age.aid = job.id AND 
             age.aid='$id'

 UNION ALL

 SELECT age.aid, 0 AS job.id, guess, COUNT(guess) AS countguess 
 FROM age 
 GROUP BY guess 
 ORDER BY countguess DESC 
 LIMIT 1
) a
GROUP BY aid

*注意:UNION ALL在两个查询中都需要相同数量的列

答案 3 :(得分:0)

SELECT age.*, job.id FROM age, job,
    (SELECT AVG(guess) AS countguess FROM age GROUP BY guess ORDER BY countguess DESC LIMIT 1) AS countguess
FROM job AS j
INNER JOIN age AS a
ON j.id = a.aid
WHERE a.aid = '{$id}'

我不确定这是不是你想要的?也许

SELECT age.*, job.id FROM age, job,
    (SELECT AVG(guess) AS countguess FROM age WHERE guess = a.guess GROUP BY '1') AS countguess
FROM job AS j
INNER JOIN age AS a
ON j.id = a.aid
WHERE a.aid = '{$id}'