繁体   English   中英

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

[英]Make a joined table's rows the field names and values of the main query?

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

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)

您可以尝试以下 - 使用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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM