使用MIN()为每个代码选择一条记录(MySQL)

时间:2017-01-06 18:14:58

标签: php mysql

[强迫症的前言-1] 我知道这个问题已被回答,至少十亿次,但问题是我无法将这些答案建模为我的答案想要获得。我不是SQL专家,这是肯定的;我对使用SELECT,UPDATE,DELETE,ecc等经典命令充满信心。所以我要感谢任何愿意帮助我的人。

说,假设我有一张像这样的表:

|----|--------|------------|----|----------|---------|---------|------|
| id |  code  |  category  | mq |  weight  |  weave  |  price  | show |
|----|--------|------------|----|----------|---------|---------|------|
| 1  | DT450R |   carbon   |  1 |   450    |  plain  |    90   |   1  |
| 2  | DT450R |   carbon   |  2 |   450    |  plain  |    40   |   1  |
| 3  | DT450R |   carbon   |  5 |   450    |  plain  |    75   |   1  |

| 4  | ZX300R |   carbon   |  1 |   300    |  plain  |    12   |   0  |
| 5  | ZX300R |   carbon   | 15 |   300    |  plain  |   128   |   1  |
| 6  | ZX300R |   carbon   | 30 |   300    |  plain  |    92   |   1  |

| 7  | PP120Q |   carbon   |  3 |   120    |  twill  |    28   |   1  |
| 8  | PP120Q |   carbon   |  7 |   120    |  twill  |    65   |   1  |
| 9  | PP120Q |   carbon   |  9 |   120    |  twill  |    49   |   1  |

我希望我的查询要做的是为每个代码选择最低价格的行:

| 2  | DT450R |   carbon   |  2 |   450    |  plain  |    40   |   1  |
| 4  | ZX300R |   carbon   |  1 |   300    |  plain  |    12   |   0  |
| 7  | PP120Q |   carbon   |  3 |   120    |  twill  |    28   |   1  |

首次尝试 (基于MySQL documentation中给出的 MIN()的解释,或者至少是基于我的内容了解它):

$sql = 'SELECT code, weight, weave, MIN(price)
        FROM products
        WHERE category="carbon" AND show="1"
        GROUP BY code
        ORDER BY weight ASC';

第二次尝试 (基于此处的this answer):

$sql = 'SELECT a.code, a.weight, a.price, a.weave
        FROM   products a
        INNER JOIN
        (
            SELECT   code, weight, MIN(price) AS minprice, weave
            FROM     products
            GROUP BY code
        ) 
       b ON a.code = b.code AND a.weave = b.weave AND a.price = b.minprice AND AND a.weight = b.weight
       WHERE category="carbon" AND show="1"
       ORDER BY a.weight ASC';

第三次尝试 (基于此处的this other answer):

$sql = 'SELECT code, weight, weave, price
        FROM products
        INNER JOIN 
        (
             SELECT MIN(price) price, code, weight, weave
             FROM products
             GROUP BY code
        ) 
        AS MIN ON MIN.code = products.code AND MIN.weight = products.weight AND MIN.weave = products.weave
        WHERE category="carbon" AND show="1"
        ORDER BY a.weight ASC';

可能无用的说这些尝试都没有产生预期的结果;只是第三种方法输出一些东西,而其他两种方法返回0 matches。我理解在第二和第三种方法中,我将查询嵌入到查询中,但我无法弄清楚它们为什么不起作用。

1 个答案:

答案 0 :(得分:2)

你的第二次尝试即将结束。但您应加入的唯一列是codepriceweightweave然后来自此连接条件选择的行。

SELECT a.code, a.weight, a.price, a.weave
FROM   products a
INNER JOIN
(
    SELECT   code, MIN(price) AS minprice
    FROM     products
    GROUP BY code
) 
b ON a.code = b.code AND a.price = b.minprice
WHERE category="carbon" AND show="1"
ORDER BY a.weight ASC

这与您链接的问题中的答案相同。他们都没有建议在ON子句中添加其他列,所以我不确定它来自哪里。