Selecting duplicate site_id's
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
This query works great, except that it's pulling duplicate site_ids....
I haven't been able to resolve this issue, this query doesn't work either:
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
Each site has many deals, but I only want the late开发者_Go百科st of each of the deals. This query is pulling 3 of 5 roles belonging to the same site.
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
The previous answer seems to be be far to complex by creating the anonymous table with a subquery. Unless I am missing something a simple group by function should do the trick:
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)
精彩评论