MySQL查询:LIMITING JOIN

时间:2020-03-06 15:02:02  来源:igfitidea点击:

假设我有两个要加入的表。
分类:

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

我想要一个返回类别和第一个(也是第一个)项目名称的查询:

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

谢谢!

解决方案

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

刚刚做了一个快速测试。这似乎可行:

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()之类的命令进行内部查询!

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)