2008-10-02 169 views
5

假设我有两个表要加入。 分类:MySQL查询:限制联接

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 

谢谢!

+0

您如何定义“第一个”?它看起来像项目中最低的ID值? – 2008-10-02 15:36:45

+0

是的,我的坏。首先,我的意思是最低的ID。 – Eikern 2008-10-02 16:07:52

回答

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) 

我认为这将满足您的第一个问题。不知道第二个 - 我认为这需要一个随机()或类似的命令内部查询!

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 
+0

当我尝试这种方法时出现错误:“每个派生表都必须有自己的别名”。 我想我在某个地方做错了什么。 – Eikern 2008-10-02 16:22:17

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)