source

조인된 테이블의 행을 기본 쿼리의 필드 이름 및 값으로 지정하시겠습니까?

factcode 2023. 9. 1. 21:22
반응형

조인된 테이블의 행을 기본 쿼리의 필드 이름 및 값으로 지정하시겠습니까?

조인된 테이블의 행을 기본 쿼리의 필드 이름과 값으로 만들 수 있습니까?구조와 데이터를 보여줌으로써 설명하겠습니다.

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의 첫 번째 행만 표시되며(syslogmyadmin), struct_fields의 필드 이름이 표시됩니다.

저는 모든 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'

언급URL : https://stackoverflow.com/questions/54941802/make-a-joined-tables-rows-the-field-names-and-values-of-the-main-query

반응형