从多个表中分组结果

问题描述 投票:0回答:2

我有6个表:3个关于动漫/漫画/ ova /的一般数据和3个他们的类型是1到m的关系

anime:                manga:                   ova:

aid | data | ... |    mid | data | ... |       oid | data | ... |
----+------+-----+    ----+------+-----+       ----+------+-----+
  1 | .... | ... |      1 | .... | ... |         1 | .... | ... | 
  2 | .... | ... |      2 | .... | ... |         2 | .... | ... |
  3 | .... | ... |      3 | .... | ... |         3 | .... | ... |
  4 | .... | ... |      4 | .... | ... |         4 | .... | ... |

anime_genre:          manga_genre:             ova_genre:

aid | genre           mid | name               oid | genre
----+--------         ----+----------          ----+--------
  1 | Ecchi             1 | Drama                1 | Action
  1 | Action            2 | Ecchi                2 | Action
  2 | Action            3 | Fighting             3 | Drama
  3 | Drama             4 | Action               4 | Ecchi
  4 | Action

我试图在有人搜索某个类型以在一个查询中获取所有信息时将结果分组

情况1:

result on genre = Action:

  genre | ids                                         
--------+---------------------------------------------
 Action | 1:anime 2:anime 4:anime 4:manga 1:ova 2:ova


result on genre = Ecchi:

  genre | ids
--------+-------------------------------
  Ecchi | 1:anime 4:anime 2:manga 4:ova

案例2(最好):

result on genre = Action:

  genre |   id    | common data | common data | common data
--------+---------+-------------+-------------+-------------
 Action | 1:anime |     ...     |     ...     |     ...
 Action | 2:anime |     ...     |     ...     |     ...
 Action | 4:anime |     ...     |     ...     |     ...
 Action | 4:manga |     ...     |     ...     |     ...
 Action | 1:ova   |     ...     |     ...     |     ...
 Action | 2:ova   |     ...     |     ...     |     ...


result on genre = Ecchi:

 genre |   id    | common data | common data | common data
-------+---------+-------------+-------------+-------------
 Ecchi | 1:anime |     ...     |     ...     |     ...
 Ecchi | 4:anime |     ...     |     ...     |     ...
 Ecchi | 2:manga |     ...     |     ...     |     ...
 Ecchi | 4:ova   |     ...     |     ...     |     ...

我一整天都在抨击我,我只能得到一张桌子所需的结果。我无法在一个查询中获得所有三个结果。

有任何想法吗?有人能指出我正确的方向吗? (数据表有一些不常见的列,但我真的不在乎我是否因为那些因为我在js中解析结果而得到空值)

mysql sql join concat nested-select
2个回答
0
投票

查找mysql join,你可以连接表并在多个表之间搜索匹配的答案。


0
投票

你可以使用id获取union alls列表:

select ag.genre, 'anime' as which, ag.aid as id
from anime_genre ag
union all
select mg.genre, 'manga' as which, mg.mid as id
from manga_genre mg 
union all
select og.genre, 'ova' as which, og.oid as id;
from ova_genre og;

您可以在子查询中加入其他列。

© www.soinside.com 2019 - 2024. All rights reserved.