簡體   English   中英

右聯接/內聯接/多選[MYSQL]表結果

[英]Right join / inner join / multiselect [MYSQL] TABLE RESULTS

我很難找到一種從另一張表中選擇一列的正確方法,並顯示一個同時包含兩個表的結果。

第一表:

id | times     | project_id |
12 | 12.24     | 40         |
13 | 13.22     | 40         |
14 | 13.22     | 20         |
15 | 12.22     | 20         |
16 | 13.30     | 40         |

第二張表:

id | times     | project_id |
32 | 22.24     | 40         |
33 | 23.22     | 40         |
34 | 23.22     | 70         |
35 | 22.22     | 70         |
36 | 23.30     | 40         |

我希望從第一個表中為project_id = 40選擇所有時間,並從第二個表中為同一個project_id = 40加入所有時間。

結果應如下所示:

id | time      | time       | project_id |
12 | 12.24     | 22.24      | 40         |
13 | 13.22     | 23.22      | 40         |
16 | 13.30     | 23.30      | 40         |

您需要在這兩個表之間使用UNION ALL ,否則您將得到不正確的結果。 將所有行放在一起后,就可以使用變量來繼承“先前值”,如下所示,並在此SQL Fiddle中進行了演示

MySQL 5.6模式設置

CREATE TABLE Table1
    (`id` int, `times` decimal(6,2), `project_id` int)
;

INSERT INTO Table1
    (`id`, `times`, `project_id`)
VALUES
    (12, 12.24, 40),
    (13, 13.22, 40),
    (14, 13.22, 20),
    (15, 12.22, 20),
    (16, 13.30, 40)
;


CREATE TABLE Table2
    (`id` int, `times` decimal(6,2), `project_id` int)
;

INSERT INTO Table2
    (`id`, `times`, `project_id`)
VALUES
    (32, 22.24, 40),
    (33, 23.22, 40),
    (34, 23.22, 70),
    (35, 22.22, 70),
    (36, 23.30, 40)
;

查詢1

select
      project_id, id, prev_time, times
from (
    select
           @row_num :=IF(@prev_value=d.project_id,@row_num+1,1) AS RowNumber
         , d.*
         , IF(@row_num %2 = 0, @prev_time, '') prev_time
         , @prev_value := d.project_id
         , @prev_time := times
     from (
          select `id`, `times`, `project_id` from Table1
          union all
          select `id`, `times`, `project_id` from Table2
          ) d
    cross join (select @prev_value := 0, @row_num := 0) vars
    order by d.project_id, d.times
    ) d2
where prev_time <> ''

結果

| project_id | id | prev_time | times |
|------------|----|-----------|-------|
|         20 | 14 |     12.22 | 13.22 |
|         40 | 13 |     12.24 | 13.22 |
|         40 | 32 |     13.30 | 22.24 |
|         40 | 36 |     23.22 |  23.3 |
|         70 | 34 |     22.22 | 23.22 |

注意:准備好此答案后,MySQL doe snot當前支持LEAD()和LAG()函數。 當MySQL確實支持這些方法時,該方法將更簡單並且可能更有效。

select
       d.*
from (
     select
            d1.*
          , LEAD(times,1) OVER(partition by project_id order by times ASC) next_time
     from (
          select id, times, project_id from Table1
          union all
          select id, times, project_id from Table2
          ) d1
      ) d
where next_time is not null

暫無
暫無

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

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