我有两个表,它们的结构如下:
表1:
+----+-----------------------+----------------------+
| id | rank_before_promotion | rank_after_promotion |
+----+-----------------------+----------------------+
| 01 | GR01 | GR02 |
| 02 | GR03 | GR04 |
| 03 | GR03 | GR05 |
| 04 | GR06 | GR07 |
+---------------------------------------------------+
表2:
+------+------+
| rank | area |
+------+------+
| GR01 | 1000 |
| GR02 | 1200 |
| GR03 | 1400 |
| GR04 | 1600 |
+-------------+
我想用这个sql来计算rank_before_promotion的区域和rank_after_promotion的区域之间的差异:
SELECT id, rank_before_promoton, rank_after_promotion, tmp1.area-tmp2.area
FROM (table1 INNER JOIN table2 ON rank_before_promotion = rank) AS tmp1,
(table1 INNER JOIN table2 ON rank_after_promotion = rank) AS tmp2;
运行此sql时出现错误。我可以重命名由join生成的表吗?是否有一种方法来打印由join生成的表?
所需的输出将是:
+----+-----------------------+----------------------+--------+
| id | rank_before_promotion | rank_after_promotion | differ |
+----+-----------------------+----------------------+--------+
| 01 | GR01 | GR02 | 200 |
| 02 | GR03 | GR04 | 200 |
| 03 | GR03 | GR05 | 400 |
| 04 | GR06 | GR07 | 200 |
+---------------------------------------------------+--------+
答案 0 :(得分:1)
我不完全明白你试图从另一个字节中减去一个字符串,但这是你执行的查询版本:
SELECT id, rank_before_promotion, rank_after_promotion, b.area-c.area
FROM table1 a
INNER JOIN table2 b
ON a.rank_before_promotion = b.rank
INNER JOIN table2 c
ON a.rank_after_promotion = c.rank;
演示:SQL Fiddle