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

nxowjjhe  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(404)

只有当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
eit6fx6z

eit6fx6z1#

你可以做一个“自左连接”匹配 id1id2 右边的table,反之亦然。
如果有匹配项(即使在不同的行中),右边的表 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

相关问题