是否可以使联接表的行成为主查询的字段名称和值? 让我通过显示结构和数据来解释这一点:
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"
这将为我提供常见类型的所有结构,以及所有对应的字段
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)
答案 0 :(得分: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'