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

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

谢谢!

有帮助吗?

解决方案

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

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 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;

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

的操作
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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top