右连接/内连接/多选[MYSQL]表结果

时间:2017-09-30 19:43:42

标签: mysql multi-select right-join

我很难找到从另一个表中选择列的正确方法,并在同一时间显示一个包含两个表的结果。

第一张表:

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         |

1 个答案:

答案 0 :(得分:1)

您需要在这两个表之间使用proxy = https://<user-name>:<password>@<proxy-host>:<port> https-proxy = https://<user-name>:<password>@<proxy-host>:<port> ,否则您将得到不正确的结果。一旦将所有行组合在一起,就可以使用变量来继承先前的值&#34;如下所示,并在此SQL Fiddle

进行了演示

MySQL 5.6架构设置

UNION ALL

查询1

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)
;

<强> Results

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 <> ''

注意:当准备好这个答案时,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
相关问题