MySQL查询:限制加入

时间:2008-10-02 15:25:59

标签: mysql sql join greatest-n-per-group

说我有两张桌子要加入。 分类:

id   name
----------
1    Cars
2    Games
3    Pencils

和项目:

id   categoryid   itemname
---------------------------
1    1            Ford
2    1            BMW
3    1            VW
4    2            Tetris
5    2            Pong
6    3            Foobar Pencil Factory

我想要一个返回类别和第一个(也是唯一的第一个)itemname的查询:

category.id category.name item.id item.itemname
-------------------------------------------------
1           Cars          1       Ford
2           Games         4       Tetris
3           Pencils       6       Foobar Pencil Factory

有没有办法可以获得随机结果,如:

category.id category.name item.id item.itemname
-------------------------------------------------
1           Cars          3       VW
2           Games         5       Pong
3           Pencils       6       Foobar Pencil Factory

谢谢!

3 个答案:

答案 0 :(得分:6)

刚做了快速测试。这似乎有效:

mysql> select * from categories c, items i
    -> where i.categoryid = c.id
    -> group by c.id;
+------+---------+------+------------+----------------+
| id   | name    | id   | categoryid | name           |
+------+---------+------+------------+----------------+
|    1 | Cars    |    1 |          1 | Ford           |
|    2 | Games   |    4 |          2 | Tetris         |
|    3 | Pencils |    6 |          3 | Pencil Factory |
+------+---------+------+------------+----------------+
3 rows in set (0.00 sec)

我认为这将满足您的第一个问题。不确定第二个 - 我认为需要一个内部查询与random()或类似的东西!

答案 1 :(得分:0)

使用Mysql可以让分组或聚合中不包含列,在这种情况下,它们具有随机值:

    select category.id, category.name, itemid, itemname
    inner join 
      (select item.categoryid, item.id as itemid, item.name as itemname
       from item group by categoryid)
    on category.id = categoryid

或者,最低限度,

select category.id, category.name, itemid, itemname
inner join 
  (select item.categoryid, min(item.id) as itemid, item.name as itemname
  from items
  group by item.categoryid)
on category.id = categoryid

答案 2 :(得分:0)

Mysql确实允许包含非聚合列,并且不保证确定性,但根据我的经验,我几乎总是得到第一个值。

通常(但不保证)这会给你第一个

select * 
from categories c, items i
where i.categoryid = c.id
group by c.id;

如果您需要保证,您需要执行类似

的操作
select categories.id, categories.name, items.id, items.name
from categories inner join
  items on items.categoryid = categories.id and 
     items.id = (select min(items2.id) from items as items2 where items2.categoryid = category.id)

如果您想要随机答案,则必须稍微更改子查询

 select categories.id, categories.name, items.id, items.name
    from categories inner join
      items on items.categoryid = categories.id and 
         items.id = (select items2.id from items as items2 where items2.categoryid = category.id order by rand() limit 1)