选择重复的site_id

时间:2011-02-27 05:33:48

标签: mysql

SELECT
    deal.*,
    site.name AS site_name
FROM deal
INNER JOIN site ON site.id = site_id
WHERE site_id IN (2, 3, 4, 5, 6)
GROUP BY deal.id DESC, site_id
LIMIT 5

这个查询效果很好,除了它提取重复的site_ids ....

我无法解决此问题,此查询也不起作用:

SELECT DISTINCT
    site.name AS site_name,
    site.woot_off,
    woot_deal.*
FROM site
INNER JOIN woot_deal ON woot_deal.site_id = site.id
WHERE site_id IN (2, 3, 4, 5, 6)
GROUP BY woot_deal.id DESC, site_id
LIMIT 5

每个网站都有很多优惠,但我只想要最新的每笔交易。此查询正在拉动属于同一站点的5个角色中的3个。

2 个答案:

答案 0 :(得分:5)

select 
    deal.*,
    site.name AS site_name
from (
    SELECT max(deal.id) as deal_id, site_id
    FROM deal
    INNER JOIN site ON site.id = deal.site_id
    WHERE site.id IN (2, 3, 4, 5, 6)
    GROUP BY site.id
) last_deals
inner join site on site.id = last_deals.site_id
inner join deal on deal.id = last_deals.deal_id
LIMIT 5

答案 1 :(得分:0)

通过使用子查询创建匿名表,以前的答案似乎很复杂。除非我遗漏了一些简单的按功能分组的东西应该做的事情:

mysql> select * from site;
+----+------------+
| id | name       |
+----+------------+
|  1 | lameone    |
|  2 | anotherone |
+----+------------+
2 rows in set (0.00 sec)

mysql> select * from deal;
+----+---------+-------+-------+
| id | site_id | name  | value |
+----+---------+-------+-------+
|  1 |       1 | best  |    10 |
|  2 |       1 | worst |     1 |
|  3 |       2 | best  |    10 |
|  4 |       2 | worst |     1 |
+----+---------+-------+-------+
4 rows in set (0.00 sec)

    mysql>\p
--------------
select s.name site
     , d.name 
     , max(d.value) value
  from deal d
     , site s
 where s.id = d.site_id
 group by s.id
 order by 1,2,3

--------------

    -> \g
+------------+------+-------+
| site       | name | value |
+------------+------+-------+
| anotherone | best |    10 |
| lameone    | best |    10 |
+------------+------+-------+
2 rows in set (0.00 sec)