多个选择连接查询,其中一个表上的相应列对其他列

时间:2014-04-07 04:31:46

标签: mysql

让我们说我有这样的表:

<b>Name</b>
+---------+--------+
| name_id | name   |
+---------+--------+
| 5       | Betti  |
| 6       | Derry  |
| 7       | Alfred |
| 8       | Elsie  |
| 9       | Cinta  |
+---------+--------+

<b>Goods</b>
+----------+-----------+
| goods_id | goods     |
+----------+-----------+
| 1        | Computer  |
| 2        | AC        |
| 3        | Microwave |
| 4        | TV        |
+----------+-----------+

<b>Transaction</b>
+-------+---------+----------+
| ai_id | name_id | goods_id |
+-------+---------+----------+
| 1     | 7       | 2        |
| 2     | 5       | 4        |
| 3     | 9       | 3        |
+-------+---------+----------+

我想用 name 列替换 Transaction 表上的 name_id 列在名称表上,其中包含相应的name_id列,因此对于goods_id,可以生成与此表类似的内容:

<b>Transaction</b>
+-------+--------+-----------+
| ai_id | name   | goods     |
+-------+--------+-----------+
| 1     | Alfred | AC        |
| 2     | Betti  | TV        |
| 3     | Cinta  | Microwave |
+-------+--------+-----------+

4 个答案:

答案 0 :(得分:0)

试试这个:

SELECT C.ai_id,A.name,B.goods
FROM Transaction C 
INNER JOIN Name A 
ON A.name_id=C.name_id
INNER JOIN Goods B 
ON B.goods_id=C.goods_id;

http://sqlfiddle.com/#!2/3c5f3/8

答案 1 :(得分:0)

尝试使用内部联接

SELECT T.ai_id,N.name,G.goods 
FROM Transaction as T
INNER JOIN Goods as G ON T.goods_id = G.goods_id
INNER JOIN Name as N ON N.name_id = T.name_id;

答案 2 :(得分:0)

如果您只是想显示信息而不是实际“替换”新表格,那么您可以使用简单SELECT的{​​{1}}查询。这样,您可以显示多个表中的列。

INNER JOIN

答案 3 :(得分:0)

试试这个

select tb3.ai_id,tb2.name,tb1.goods from  Goods tb1,Name tb2,Transaction tb3 where tb3.name_id=tb2.name_id and tb3.goods_id=tb1.goods_id order by tb3.ai_id