Mysql 困难的sql请求

Mysql 困难的sql请求,mysql,sql,Mysql,Sql,我在sql请求方面遇到了一些问题 这是我的桌子: 正文: id component_kind text 56 4 a 19 4 a 10 4 a 1 6 b 行为: ItemGather: id item_id count 2 1020 3 怪物狩猎: id

我在sql请求方面遇到了一些问题

这是我的桌子:

正文:

id     component_kind     text
56           4             a
19           4             a
10           4             a
1            6             b
行为:

ItemGather:

id     item_id    count
 2      1020        3
怪物狩猎:

id     npc_id   count
 5      256      10
项目用途:

id    item_id   count
 6     3241       1
如您所见,act.text_id是text.id的外键,而act.detail_id表示act下面一个表的id

我想做的是展示这样的东西:

component_kind text gather_id gather_count use_id use_count hunt_id hunt_count
       4        a      1020        3        3241      1       256      10
       6        b       0          0          0       0        0        0

我不知道在我的请求中写什么。任何sql pro都能帮我吗?

如上面的注释所述,只需外部连接表即可

如果存在多个匹配项,我使用GROUP_CONCAT。在MySQL中,可以简单地选择ig.item_id,而不是group_concatig.item_id,如果有多个id,它会给您一个随机id。在这种情况下,你想展示什么取决于你自己

当没有匹配的记录时,我使用COALESCE来显示0,而不是NULL

select
  t.component_kind,
  t.text,
  group_concat(ig.item_id) as gather_ids,
  coalesce(sum(ig.count),0) as gather_count,
  group_concat(iu.item_id) as use_ids,
  coalesce(sum(iu.count),0) as use_count,
  group_concat(mh.npc_id) as hunt_is,
  coalesce(sum(mh.count),0) as hunt_count
from text t
left outer join act a on a.text_id = t.id
left outer join itemgather ig on ig.id = a.detail_id and a.detail_type = 'ItemGather'
left outer join monsterhunt mh on mh.id = a.detail_id and a.detail_type = 'MonsterHunt'
left outer join itemuse iu on iu.id = a.detail_id and a.detail_type = 'ItemUse'
group by t.component_kind, t.text;

下面是SQL FIDLE:。

您的实际问题是什么?您必须将三个详图表连接起来。这已经回答了你的问题吗?还不清楚选择gather\u id、hunt\u id、use\u id和同时应用GROUP BY子句的逻辑是什么好的,你加入所有的表,然后按text.component\u种类和text.text分组。试试看。把你的数据放在www.sqlfiddle.com上,你会得到更好的响应,也请标记你正在使用的sql,oracle,mssql或mysqlI试图外部联接表,但我得到了sql语法错误。然后我尝试了一个内部连接,请求被正确处理,但没有返回任何结果。
select
  t.component_kind,
  t.text,
  group_concat(ig.item_id) as gather_ids,
  coalesce(sum(ig.count),0) as gather_count,
  group_concat(iu.item_id) as use_ids,
  coalesce(sum(iu.count),0) as use_count,
  group_concat(mh.npc_id) as hunt_is,
  coalesce(sum(mh.count),0) as hunt_count
from text t
left outer join act a on a.text_id = t.id
left outer join itemgather ig on ig.id = a.detail_id and a.detail_type = 'ItemGather'
left outer join monsterhunt mh on mh.id = a.detail_id and a.detail_type = 'MonsterHunt'
left outer join itemuse iu on iu.id = a.detail_id and a.detail_type = 'ItemUse'
group by t.component_kind, t.text;