簡體   English   中英

SQL - 連接同一個表中的行

[英]SQL - joining rows from same table

我只知道最簡單的SQL,所以請把我當成一個完整的菜鳥吧!

我有一個有很多行的表,但有些可以通過id配對,我想要合並這些行的返回數組。

 post_id  # meta_name # meta_value  #     
======================================
   1      #   bar     #    44       #
   1      #   foo     #    on       #
   2      #   bar     #    1        #
   2      #   foo     #    on       #
   3      #   bar     #    1        #
   3      #   foo     #    off      #

作為縮小版本,想象一下我的表格,我的目標是返回2個結果

   1    #   foo    #  bar    #   44   #  on
   2    #   foo    #  bar    #   1    #  on

基於ids相關且c2的值為'on'

我的嘗試是從一些閱讀,但沒有得到任何地方的以下

SELECT 
    t1.post_id, t2.post_id, t1.meta_name, t2.meta_name, t1.meta_value, t2.meta_value 
FROM 
    `ecom_page_meta` t1 
JOIN 
    `ecom_page_meta` t2 
ON 
    t1.post_id = t2.post_id 
WHERE 
    t1.meta_name = 'featured-products' 
AND 
    t1.meta_value = 'on'

任何幫助將非常感激

**編輯**

我想我只是發布了下面的答案得到了很好的語法:

SELECT L.post_id, L.meta_name, R.meta_name, L.meta_value, R.meta_value
FROM `ecom_page_meta` L
INNER JOIN ecom_page_meta R
    ON L.post_id = R.post_id
    AND L.meta_name = 'featured-products-order' 
    AND R.meta_value = 'on' 
WHERE R.meta_name = 'featured-products' 
ORDER BY L.meta_value 
DESC

再次感謝。

創建測試數據:

SQL> create table ecom_page_meta (post_id number not null
  2      , meta_name varchar2(15) not null
  3      , meta_value varchar2(15) not null);

Table created.

SQL> insert into ecom_page_meta values (1, 'bar', '44');

1 row created.

SQL> insert into ecom_page_meta values (1, 'foo', 'on');

1 row created.

SQL> insert into ecom_page_meta values (2, 'bar', '1');

1 row created.

SQL> insert into ecom_page_meta values (2, 'foo', 'on');

1 row created.

SQL> insert into ecom_page_meta values (3, 'bar', '1');

1 row created.

SQL> insert into ecom_page_meta values (3, 'foo', 'off');

1 row created.

SQL> commit;

Commit complete.

查詢以給出匹配OP樣本的結果:

SQL> select L.post_id, L.meta_name, R.meta_name, L.meta_value, R.meta_value
  2  from ecom_page_meta L
  3  inner join ecom_page_meta R
  4      on L.post_id = R.post_id
  5      and L.meta_value <> 'on'
  6      and R.meta_value = 'on'
  7  where L.meta_name = 'bar';

   POST_ID META_NAME       META_NAME       META_VALUE      META_VALUE
---------- --------------- --------------- --------------- ---------------
         1 bar             foo             44              on
         2 bar             foo             1               on

我仍然不知道什么是WHERE t1.meta_name = 'featured-products'與任何事情有關,因為沒有樣本數據包括字符串'featured-products'的t1.meta_name。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM