php - 通过内连接查找前 3 个值

标签 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 个最高值,其中 users 表中的 username 具有 balance 值大于或等于 5。我知道我需要进行某种内部联接,但下面的查询不起作用。这是我的查询:

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

我觉得这应该很简单,但我遇到了困难!感谢您的帮助

最佳答案

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

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

关于php - 通过内连接查找前 3 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10450818/

相关文章:

php - Codeigniter 连接 4 个表

php - 在 Laravel 5 中发送大量数组数据时 RouteCollection.php 中的 MethodNotAllowedHttpException 错误

php - 数据库连接错误(1) : The MySQL adapter 'mysql' is not available

php - 管理 CodeIgniter 中的 "A Database Error Occurred"1062 错误

mysql - 如何通过对mysql中另一个表中的字段进行分组来从两个不同的表中获取两个字段的计数

PHP & MySQL : using group by for categories

php - 如何在php中修改上传文件的内容类型?

php - PHP 中的多个 paamayim nekudotayims,为什么不呢?

php - 如何将内容加载到类似灯箱的叠加层中

mysql - SQL 和 MySQL 有什么区别?