문제

가입하고 싶은 테이블 두 개가 있다고 말합니다. 카테고리 :

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