여러 행이 다른 테이블의 컬럼에서 연결하여 행입니다

mrtkprc :

나는 WooCommerce 관련 응용 프로그램을 개발했습니다. 따라서, 나는 WooCommerce의 데이터베이스 테이블을 사용해야합니다.

나는 점에 붙어입니다. 나는 foreign_id 한 여러 행이 다른 테이블에 테이블을 연결하고 싶습니다.

예를 들면 :

WooCommerce 2 개 테이블이 있습니다. 이들은 wp_postswp_postmeta.

wp_posts다음 표가 포함되어 있습니다.

| ID   | post_title | post_name
| 1682 | foo        | foo
| 1681 | bar        | bar

wp_postmeta다음 표가 포함되어 있습니다.

| post_id | meta_key              | meta_value
| 1682    | _regular_price        | 100
| 1682    | _sale_price           | 99
| 1681    | _regular_price        | 300
| 1681    | _sale_price           | 299

나는 테이블을 다음과 같은 결과 SQL 쿼리를 작성하고 싶습니다.

| ID   | post_title | post_name  | _regular_price | _sale_price |
| 1682 | foo        | foo        | 100            | 99
| 1681 | bar        | bar        | 300            | 299

정말 고맙습니다.

모두 제일 좋다,

GMB :

조건부 집계를 사용 :

select
    p.id,
    p.post_title,
    p.post_name,
    max(case when m.meta_key = '_regular_price' then m.meta_value end) regular_price,
    max(case when m.meta_key = '_sale_price'    then m.meta_value end) sale_price
from wp_posts p
inner join wp_postmeta m on m.post_id = p.id
group by p.id, p.post_title, p.post_name

메타 테이블이 포스트 당 많은 수의 행이있는 경우, 다음과 쿼리 최적화 할 수 있습니다 where절 :

where m.meta_key in ('_regular_price', '_sale_price')

추천

출처http://43.154.161.224:23101/article/api/json?id=298905&siteId=1