在一列中具有相同名称且在其他列中具有相同ID的组值

时间:2017-10-19 14:41:13

标签: mysql sql phpmyadmin

我有以下情况:

使用我当前的查询,这就是我获取数据的方式:

enter image description here

问题是我想要将straatplaatsnaam合并,并将它们作为一行读取。每个straat与其value_item_id对应的plaatsnaam具有相同的内容。

是否可以straatplaatsnaamvalue_item_id组合在一起?

我当前的查询如下所示:

SELECT fields.id as field_id,
       fields.name,
       fields_categories.field_id as catfield_id,
       fields_values.field_id as fieldvalue_id,
       fields_values.item_id as value_item_id,
       fields_values.value,
       content.id as content_id
FROM snm_fields fields
INNER JOIN snm_fields_categories fields_categories
ON fields.id = fields_categories.field_id
INNER JOIN snm_fields_values fields_values
ON fields_categories.field_id = fields_values.field_id
INNER JOIN snm_content content
ON content.id = fields_values.item_id
WHERE fields.name in ('straat', 'plaatsnaam')

最后,我希望Ridderstraat 5Heenvliet位于同一行。我知道这也可以用PHP完成,但我认为直接用SQL做这个更好。

3 个答案:

答案 0 :(得分:1)

您可以在已过滤的表格上使用联接

  SELECT 
        fields1.id as field_id
      , fields1.name
      , fields1_categories.field_id as catfield_id
      , fields1_values.field_id as fieldvalue_id
      , fields1_values.item_id as value_item_id
      , fields1_values.value
      , content.id as content_id
      , fields2.id as field_id
      , fields2.name
      , fields2_categories.field_id as catfield_id
      , fields2_values.field_id as fieldvalue_id
      , fields2_values.item_id as value_item_id
      , fields2_values.value
  FROM snm_fields fields1
  INNER JOIN (
      SELECT 
            fields.id as field_id
          , fields.name
          , fields_categories.field_id as catfield_id
          , fields_values.field_id as fieldvalue_id
          , fields_values.item_id as value_item_id
          , fields_values.value
      FROM snm_fields fields
      WHERE fields.name  = 'plaatsnaam')

    ) on field2  ON field1.value_item_id = field2.value_item_id
  INNER JOIN snm_fields_categories fields_categories ON fields.id = fields_categories.field_id
  INNER JOIN snm_content content
  WHERE fields.name = 'straat'

答案 1 :(得分:1)

使用GROUP_CONCAT功能。

SELECT value_item_id,
      GROUP_CONCAT(name SEPARATOR ' ') as grouped_name,
      GROUP_CONCAT(value SEPARATOR ' ') as grouped_value,
FROM (the_query) src
GROUP BY value_item_id

答案 2 :(得分:1)

看起来你只需要item_id的plaats和straat。如果是这样,只需从表snm_fieldssnm_fields_values中读取就足够了。使用条件聚合item_id

select 
  fv.item_id, 
  max(case when f.name = 'plaatsnaam' then fv.value end) as plaats,
  max(case when f.name = 'straat' then fv.value end) as straat
from snm_fields_values fv 
join snm_fields f on f.id = fv.field_id
group by fv.item_id
order by fv.item_id, plaats, straat;

或者,如果你可以让你的查询知道ID,甚至可以:

select 
  item_id, 
  max(case when field_id = 3 then value end) as plaats,
  max(case when field_id = 1 then value end) as straat
from snm_fields_values
group by item_id
order by item_id, plaats, straat;