简化问题,我有两个表 - item 和 item_info。
项目如下所示:
+-----+----------+
| id | title |
+-----+----------+
| 1 | lorem1 |
| 2 | lorem2 |
| 3 | lorem3 |
| 4 | lorem4 |
| 5 | lorem5 |
+-----+----------+
item_info 看起来像这样:
+-----+----------+---------------+---------------+
| id | item_id | field_name | field_value |
+-----+----------+---------------+---------------+
| 1 | 1 | tag | a_tag1 |
| 2 | 1 | tag | a_tag2 |
| 3 | 1 | series_title | bob_show |
| 4 | 1 | tag | b_tag1 |
| 5 | 1 | tag | b_tag2 |
| 6 | 2 | tag | a_tag3 |
| 7 | 2 | tag | a_tag4 |
| 8 | 2 | series_title | jane_show |
| 9 | 2 | tag | b_tag3 |
| 10 | 2 | tag | b_tag4 |
+-----+----------+---------------+---------------+
我试图得到一个看起来像这样的结果:
+-----+----------+---------------+---------------+---------------+
| id | title | series_title | a_tags | b_tags |
+-----+----------+---------------+---------------+---------------+
| 1 | lorem1 | bob_show | a_tag1,a_tag2 | b_tag1,b_tag2 |
| 2 | lorem2 | jane_show | a_tag3,a_tag4 | b_tag3,b_tag4 |
+-----+----------+---------------+---------------+---------------+
我需要将结果集限制为 item.id 行的特定列表。我正在尝试使用多个左连接来做到这一点:
select i.id as 'id', i.title as 'title', info.field_value as 'series_title',
GROUP_CONCAT(DISTINCT info2.field_value) as 'a_tags',
GROUP_CONCAT(DISTINCT info3.field_value) as 'b_tags'
from item i
left join item_info info on i.id = info.item_id
left join item_info info2 on i.id = info2.item_id
left join item_info info3 on i.id = info3.item_id
and i.id in (1,2)
where info.field_name = 'series_title'
or info2.field_name = 'tag'
and info2.field_value like "a_%"
or info3.field_name = 'tag'
and info3.field_value like "b_%"
group by 1;
我不知道这是否有效,因为查询会永远持续下去,而当我们运行永远持续下去的查询时,我的操作人员会变得暴躁。谁能帮我简化查询并确保我以正确的方式构建它?