我有以下情况:
使用我当前的查询,这就是我获取数据的方式:
问题是我想要将straat
和plaatsnaam
合并,并将它们作为一行读取。每个straat
与其value_item_id
对应的plaatsnaam
具有相同的内容。
是否可以straat
和plaatsnaam
将value_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 5
和Heenvliet
位于同一行。我知道这也可以用PHP完成,但我认为直接用SQL做这个更好。
答案 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_fields
和snm_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;