使连接表的行成为主查询的字段名称和值?

问题描述 投票:1回答:1

是否可以使连接表行的主要查询的字段名称和值?让我通过显示结构和数据来解释:

structs
    id
    type

struct_fields
    id
    struct_id
    name
    value

示例数据:

structs
    1, faq
    2, faq
    3, post

struct_fields
    1, 1, "question", "Will there be food?" 
    2, 1, "answer", "No, you will have to bring your own food"
    3, 1, "active", 1
    4, 2, "question", "Will there be drinks?"
    5, 2, "answer", "Yes, there will be plenty of drinks"
    6, 2, "active", 0
    7, 3, "title", "Great post!"
    8, 3, "body", "Lorum ipsum..."
    9, 3, "published", "2019-01-01 23:12:00"

这将给我所有类型faq的结构,包括所有相应的字段

SELECT s.*, f.*
FROM `structs` s
RIGHT JOIN `struct_fields` f ON f.struct_id = s.id
WHERE s.type = 'faq' 

但是我的行显然是双倍的,因为所有生成行的struct_fields也是如此

但是当我补充说

GROUP BY s.id 

仅显示匹配的struct_fields的第一行(phpmyadmin),并显示struct_fields的字段名称。

我希望能够选择所有结构,包含所有相应的struct_fields,其中struct_fields名称将是结果中的字段名称,struct_field值是值,这样我就可以使用HAVING进行子选择。所以:

结果:

id, type, question,                answer,          active
1,  faq,  "Will there be food?",   "No, you...",    1
2,  faq,  "Will there be drinks?", "Yes, there...", 0

所以现在我可以使用以下内容扩展查询:

例如:HAVING active = 1 (or WHERE active = 1)

如果发布例如:WHERE published > DATE_SUB(NOW(), INTERVAL 1 DAY)

mysql sql database mariadb
1个回答
1
投票

你可以尝试下面 - 使用conditional aggregation and Join

select s.id,s.type,question, answer, active from FROM `structs` s
inner join
(
select struct_id, max(case when name='question' then value end) as question,
max(case when name='answer' then value end) as answer,
max(case when name='active' then value end) as active
from struct_fields group by struct_id
)f ON f.struct_id = s.id WHERE s.type = 'faq'
© www.soinside.com 2019 - 2024. All rights reserved.