반응형
조인된 테이블의 행을 기본 쿼리의 필드 이름 및 값으로 지정하시겠습니까?
조인된 테이블의 행을 기본 쿼리의 필드 이름과 값으로 만들 수 있습니까?구조와 데이터를 보여줌으로써 설명하겠습니다.
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
반응형
'source' 카테고리의 다른 글
Visual Studio Code 내에서 Git 사용자 변경 (0) | 2023.09.01 |
---|---|
http 컨텍스트를 사용하지 않고 응용 프로그램 경로를 가져옵니다.(asp.net ) (0) | 2023.09.01 |
CCU가 최대 500개인 애플리케이션에 대해 이 판독값이 괜찮습니까? (0) | 2023.09.01 |
mysql-native 드라이버를 사용하여 DB에 연결한 후 예외 발생 (0) | 2023.09.01 |
Android에서 EditText를 숫자 값만 허용하도록 설정하려면 어떻게 해야 합니까? (0) | 2023.09.01 |