mysql加入不同的领域

时间:2019-07-10 09:49:01

标签: mysql

我基本上有两个表:

id    pk_id     status
1     2162125   open    
2     2162125   fixed   
3     2162125   released
4     2162125   closed  

id  pk_id       type            date
1   2162125     date_close      2018-11-09 18:15:17.212
2   2162125     date_fix        2018-11-09 18:14:37.139
3   2162125     date_confirm    2018-11-09 18:14:11.746

第一个表具有状态,第二个表具有状态更改的日期时间。我需要找到一种方法来连接这两个表,以便将fixed与fix_date值,date_close值等相关。

非常有限,我无法创建新表或更改类型值,否则我将使用相同的名称来对其进行命名。

编辑,这是预期的输出:

id    pk_id     status    type           date
1     2162125   open      null           null 
2     2162125   fixed     date_fix       2018-11-09 18:14:37.139
3     2162125   released  null           null
4     2162125   closed    date_close     2018-11-09 18:15:17.212

3 个答案:

答案 0 :(得分:1)

您可以尝试使用左联接

select a.id,a.pk_id,a.status,b.type,b.date
from table1 a left join table2 
on a.status like concat(concat('%',replace(b.type,'date_','')),'%')

答案 1 :(得分:1)

您可以用状态连接'date_'并用'%'连接类型并将其用作连接子句:

模式(MySQL v5.7)

CREATE TABLE table1 (
  `id` INTEGER,
  `pk_id` INTEGER,
  `status` VARCHAR(8)
);

INSERT INTO table1
  (`id`, `pk_id`, `status`)
VALUES
  (1, 2162125, 'open'),
  (2, 2162125, 'fixed'),
  (3, 2162125, 'released'),
  (4, 2162125, 'closed');



CREATE TABLE table2 (
  `id` INTEGER,
  `pk_id` INTEGER,
  `type` VARCHAR(12),
  `date` VARCHAR(23)
);

INSERT INTO table2
  (`id`, `pk_id`, `type`, `date`)
VALUES
  (1, 2162125, 'date_close', '2018-11-09 18:15:17.212'),
  (2, 2162125, 'date_fix', '2018-11-09 18:14:37.139'),
  (3, 2162125, 'date_confirm', '2018-11-09 18:14:11.746');

查询#1

SELECT t1.id,
       t1.pk_id,
       t1.status,
       t2.type,
       t2.date
FROM table1 t1
LEFT JOIN table2 t2
ON t1.pk_id = t2.pk_id
AND CONCAT('date_', t1.status) LIKE CONCAT(t2.type, '%')
ORDER BY t1.id;

输出

| id  | pk_id   | status   | type       | date                    |
| --- | ------- | -------- | ---------- | ----------------------- |
| 1   | 2162125 | open     |            |                         |
| 2   | 2162125 | fixed    | date_fix   | 2018-11-09 18:14:37.139 |
| 3   | 2162125 | released |            |                         |
| 4   | 2162125 | closed   | date_close | 2018-11-09 18:15:17.212 |

View on DB Fiddle

答案 2 :(得分:0)

具有特定where子句的SELECT的联合可以解决问题:

FROM status s
JOIN change c ON c.pk_id=s.pk_id
WHERE s.status = "closed" and c.type = "date_close"
UNION
SELECT s.pk_id, s.status, c.type, c.date
FROM status s
JOIN change c ON c.pk_id=s.pk_id
WHERE s.status = "fixed" and c.type = "date_fix"
...