从不同的列中选择相同的值

时间:2018-11-18 16:41:52

标签: mysql

仅在id1等于id2时,即使在不同的行中,我也必须在data2中插入data1的值。

MySql

Example
    +---------------------------+
    |          MyTable          |
    +---------------------------+
    | id1 | id2 | data1 | data2 |
    +-----+-----+-------+-------+
    |  1  |  2  | data1 |   0   |
    +-----+-----+-------+-------+
    |  2  |  1  | data2 |   0   |
    +-----+-----+-------+-------+
    |  3  |  4  | data3 |   0   |
    +-----+-----+-------+-------+
    |  4  |  3  | data4 |   0   |
    +-----+-----+-------+-------+
    |  5  |  6  | data5 |   0   |
    +-----+-----+-------+-------+

这是结果的一个例子

    +---------------------------+
    |          MyTable          |
    +---------------------------+
    | id1 | id2 | data1 | data2 |
    +-----+-----+-------+-------+
    |  1  |  2  | data1 |   0   |
    +-----+-----+-------+-------+
    |  2  |  1  | data2 | data1 |
    +-----+-----+-------+-------+
    |  3  |  4  | data3 |   0   |
    +-----+-----+-------+-------+
    |  4  |  3  | data4 | data3 |
    +-----+-----+-------+-------+
    |  5  |  6  | data5 |   0   |
    +-----+-----+-------+-------+


CREATE TABLE IF NOT EXISTS `MyTable` (
  `id1` int(6) NULL,
  `id2` int(6) NULL,
  `data1` varchar(50) NULL,
  `data2` varchar(50) NULL,
  PRIMARY KEY (`id1`)
) DEFAULT CHARSET=utf8;
INSERT INTO `MyTable` (`id1`, `id2`, `data1`, `data2`) VALUES
  ('1', '2', 'data1','0' ),
  ('2', '1', 'data2','0'),
  ('3', '4', 'data3','0'),
  ('4', '3', 'data4','0'),
  ('5', '6', 'data5','0');

也许有其他解决方案不使用COALESCE(),也排除了id2等于id1的行,并且仅包括id1等于id2的行

  SELECT
  t1.id1, 
  t1.id2, 
  t1.data1, 
  COALESCE(t2.data1, t1.data2) AS `data2`
FROM MyTable AS t1
LEFT JOIN MyTable AS t2
  ON t1.id1 = t2.id2 AND 
     t1.id2 = t2.id1 

Result
id1 id2 data1   data2
1   2   data1   data2
2   1   data2   data1
3   4   data3   data4
4   3   data4   data3
5   6   data5   0

1 个答案:

答案 0 :(得分:0)

您可以进行“自动左联接”,将id1与右侧表的id2匹配,反之亦然。

如果存在匹配项(即使在不同的行中),则右侧表data1将不会是null。然后,我们可以使用它代替data2

SELECT
  t1.id1, 
  t1.id2, 
  t1.data1, 
  COALESCE(t2.data1, t1.data2) AS `data2`
FROM your_table AS t1
LEFT JOIN your_table AS t2
  ON t1.id1 = t2.id2 AND 
     t1.id2 = t2.id1