3

我在具有两列主键的特定表中遇到 GROUP BY 查询问题。

我的表如下所示:

   CREATE TABLE IF NOT EXISTS `stocks` (
      `id_city` int(10) NOT NULL,
      `id_prod` int(10) NOT NULL,
      `sell_price` int(10) DEFAULT '0',
      PRIMARY KEY (`id_city`,`id_prod`)
    )

假设它插入了这样的值:

INSERT INTO `stocks` (`id_city`, `id_prod`, `sell_price`) 
VALUES ('1', '1', '100'), ('2', '1', '90'), ('3', '1', '10');

经过这样的查询:

SELECT id_prod, id_city, MIN(sell_price)
            FROM stocks 
            GROUP BY id_prod

结果行丢失了 'id_city' 键 - 它需要 city_id 的第一次出现,

id_prod     id_city     MIN(sell_price)
1           1           10

如何为这种情况建立适当的查询?结果应如下所示:

id_prod     id_city     MIN(sell_price)
1           3           10
4

3 回答 3

2

如果要返回包含 的记录,min(sell_price)可以使用子查询:

SELECT s1.id_prod, 
  s1.id_city, 
  s1.sell_price
FROM stocks s1
inner join
(
  select id_prod,  MIN(sell_price) sell_price
  from stocks
  group by id_prod
) s2
  on s1.id_prod = s2.id_prod
  and s1.sell_price = s2.sell_price

请参阅带有演示的 SQL Fiddle

这将返回:

| ID_PROD | ID_CITY | SELL_PRICE |
----------------------------------
|       1 |       3 |         10 |
于 2013-01-10T13:50:59.100 回答
1

你的意思是这样使用max(id_city)

    SELECT id_prod, max(id_city) city , MIN(sell_price)
        FROM stocks 
        GROUP BY id_prod 

sql演示

或喜欢使用count(id_city)

     SELECT id_prod, count(id_city) city, MIN(sell_price)
        FROM stocks 
        GROUP BY id_prod 

sql演示

两者都返回

  ID_PROD   CITY    MIN(SELL_PRICE)
      1        3                10

编辑

试试这个INNER JOIN

   SELECT s.id_prod, 
          s.id_city, 
          s.sell_price
   FROM stocks s
   inner join
             (
              select id_prod,  MIN(sell_price) sell_price
              from stocks
               group by id_prod
              ) s1
     on s.id_prod = s1.id_prod
     and s.sell_price = s1.sell_price

演示 SQLFIDDLE

于 2013-01-10T13:53:04.987 回答
0

您还必须添加id_city到该GROUP BY子句

http://www.w3schools.com/sql/sql_groupby.asp

于 2013-01-10T13:46:59.723 回答