mysql映射两个表

时间:2019-06-28 02:30:46

标签: mysql database

如何映射两个表?

表tableA:

+------------------+-----------------------+------+-----+---------------------+-------------------------------+
| Field            | Type                  | Null | Key | Default             | Extra                         |
+------------------+-----------------------+------+-----+---------------------+-------------------------------+
| id               | int(10)      | NO   | PRI | NULL                | auto_increment                |
| name             | varchar(255) | YES  |     | NULL                |                               |
| price            | decimal(8,2) | NO   |     | NULL                |                               |
+------------------+-----------------------+------+-----+---------------------+-------------------------------+

+------+------------+
| id | name | price |
+------+------------+
12 | foo   |    0.12 |
2 | barr   |    0.20 |
+------+------------+

表tableB:

+------------+-----------------------+------+-----+---------------------+-------------------------------+
| Field      | Type                  | Null | Key | Default             | Extra                         |
+------------+-----------------------+------+-----+---------------------+-------------------------------+
| id         | int(10)      | NO   | PRI | NULL                | auto_increment                |
| user_id    | int(10)      | NO   |     | NULL                |                               |
| service_id | int(10)      | NO   |     | NULL                |                               |
| price      | decimal(8,2) | NO   |     | NULL                |                               |
+------------+-----------------------+------+-----+---------------------+-------------------------------+


+------------+------------+
| user_id | service_id | price |
+------------+------------+
| 2       |          12 |  0.01 |
+------------+------------+

查询获取用户映射时。就像“ SELECT price FROM tableA”一样,需要返回tableB列值。

结果示例:

+------+------------+
| id | name | price |
+------+------------+
12 | foo   |    0.01 |
+------+------------+

2 个答案:

答案 0 :(得分:0)

通过映射两个表,您真正的意思是什么?主要有三种映射方法。

答案 1 :(得分:0)

基于“示例结果”,您尝试将TableATableBid链接到service_id。在这种情况下,您可以通过运行此查询来获得结果

Select ta.id,ta.name,tb.price 
from TableA ta,TableB tb Where
ta.id = tb.service_id;

上面的查询提供了表的关系。