2008-10-02 167 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)