在MySQL中为2个不同的表创建一个别名列

blu*_*lue 8 mysql sql select if-statement

我有一个数据库表,它与2个不同的表相关,例如:

   === inventory ===
+------------+-----------+
|    code    |   total   |
+------------+-----------+
| el_pr_25   |     45    |
| el_pr_11   |     33    |
| mob_tp_x93 |     23    |
| mob_tp_t55 |     33    |
| el_pr_x73  |     25    |
| mob_tp_25  |     22    |
+------------+-----------+

= electricity =
+-----+-------+
|  id | name  |
+-----+-------+
|  25 | test1 |
|  11 | test2 |
| x73 | test3 |
+-----+-------+

  == mobile ==
+-----+----------+
|  id |   name   |
+-----+----------+
| x93 | test 66  |
| t55 | test 222 |
| 25  | test 323 |
+-----+----------+
Run Code Online (Sandbox Code Playgroud)

我要选择的主表是库存表,库存表通过code列连接到另一个表,对于电表有一个el_pr_前缀后跟id电表,对于移动表,前缀是mob_tp_前缀,我想要从电力和移动表中选择名称列的库存表,例如结果将如下所示:

SELECT code,total, ... as name FROM inventory; 


         === inventory ===
+------------+-----------+----------+
|    code    |   total   |  name    |
+------------+-----------+----------+
| el_pr_25   |     45    | test1    |
| el_pr_11   |     33    | test2    |
| mob_tp_x93 |     23    | test 66  |
| mob_tp_t55 |     33    | test 22  |
| el_pr_x73  |     25    | test3    |
| mob_tp_25  |     22    | test 323 |
+------------+-----------+----------+
Run Code Online (Sandbox Code Playgroud)

Tim*_*sen 6

我们可以尝试以下连接查询:

SELECT
    i.code,
    i.total,
    COALESCE(e.name, m.name) AS name
FROM inventory i
LEFT JOIN electricity e
    ON i.code REGEXP CONCAT('el_.*_', e.id, '$')
LEFT JOIN mobile m
    ON i.code REGEXP CONCAT('mob_.*', m.id, '$');
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

演示

上面的查询使用COALESCE技巧为每个项目选择正确的名称,这假定给定项目只与electricitymobile表格匹配.

但是,您的数据库设计并不理想.只有一个包含移动和电子(和其他)项目元数据的表会好得多.在addtion,你的表应该有适当的加入哪些列并不需要复杂的字符串或正则表达式操作相匹配.我建议如下:

inventory
+----+------------+-----------+
| id |    code    |   total   |
+----+------------+-----------+
| 1  | el_pr_25   |     45    |
| 2  | el_pr_11   |     33    |
| 3  | el_pr_x73  |     25    |
| 4  | mob_tp_x93 |     23    |
| 5  | mob_tp_t55 |     33    |
| 6  | mob_tp_25  |     22    |
+----+------------+-----------+

items
+--------------+----------+-------------+
| inventory_id | name     | type        |
+--------------+----------+-------------+
| 1            | test1    | electricity |
| 2            | test2    | electricity |
| 3            | test3    | electricity |
| 4            | test 66  | mobile      |
| 5            | test 222 | mobile      |
| 6            | test 323 | mobile      |
+--------------+----------+-------------+
Run Code Online (Sandbox Code Playgroud)