使用内部联接查找前3个值

时间:2012-05-04 14:28:15

标签: php mysql

我有一个名为users_preferred_zips的表,如下所示:

 username  |  price  |   zip   |  program  |  active
-----------+---------+---------+-----------+---------
 joe       |    5    |  92108  |  dog      |    1
 tom       |    7    |  92108  |  dog      |    1
 mary      |    5    |  92108  |  dog      |    1
 paul      |    6    |  92108  |  dog      |    1
 ron       |    6    |  92108  |  dog      |    1

我有另一个名为users的表,看起来像这样

 username  |  balance
-----------+----------
 joe       |    10
 tom       |    12
 mary      |    2
 paul      |    14
 ron       |    3

我需要一个查询来从users_preferred_zips表中提取和求和3个最高值,其中username表中的users的{​​{1}}值大于或等于balance到5.我知道我需要做某种inner join但我的查询不起作用。这是我的查询:

SELECT SUM(price) AS SumOfTopValues
FROM (
    SELECT users_preferred_zips . * , users.last_purchase, users.lesson_type, users.pref_acct_balance
    INNER JOIN users ON ( users_preferred_zips.username = users.username ) 
    WHERE users_preferred_zips.zip =  '92108'
    AND users_preferred_zips.program =  'dog'
    AND users_preferred_zips.active =  1
    AND users.pref_acct_balance >= '5'
    ORDER BY price DESC
    LIMIT 3
) AS sub

因此,正确的查询将提取以下内容:

3最高:

joe   |  5
tom   |  7
paul  |  6

3个最高值的总和= 18

我觉得这应该很简单,但我很难过!谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

您可以使用以下方式检查:

SELECT SUM(price) AS SumOfTopValues
FROM users_preferred_zips
WHERE username IN (
  SELECT username
  FROM users
  WHERE pref_acct_balance >= 5
)