1

我有两张桌子:

表格1:

---------------------------
|id_column1 | name_column |
---------------------------
|        1  | my_name1    |
|        2  | my_name2    |
---------------------------

表2:

--------------------------------------
|id_column2 | surname_column | fk_id1|
--------------------------------------
|      111  | my_surname1    | 1     |
|      222  | my_surname2    | 2     |
--------------------------------------
fk_id1 is foreign key referenced to table1.id_column1

SELECT * FROM table1 WHERE fk_id1=1;

--------------------------------------
|id_column2 | surname_column | fk_id1|
--------------------------------------
|      111  | my_surname1    | 1     |

我怎样才能得到这个(是否有可能加入两个表列作为结果):

------------------------------------------------
|id_column2 | surname_column | fk_id1| name    |
------------------------------------------------
|      111  | my_surname1    | 1     |my_name1 |

如下所示:

SELECT * FROM table2 WHERE fk_id1=1 AND SELECT name FROM table1 WHERE id_column1=1;
4

3 回答 3

5
SELECT id_column2,surname_column,fk_id1,name_column FROM table1,table2 WHERE table1.id_column1=table2.fk_id1 AND table1.id_column1=1;
于 2013-02-01T09:19:56.800 回答
5

你的意思是这样的?

SELECT t2.*, t1.name_column 
FROM table2 t2 
     INNER JOIN table1 t1 on t2.fk_id1 = id_column1 
WHERE t1.id_column1 = 1

这是一个用于测试的示例SQL Fiddle 。

于 2013-02-01T09:20:34.217 回答
1

这很简单。可以使用内部联接来完成。

SELECT id_column2,surname_column,fk_id1,name_column as name FROM table1 Inner Join table2 on table1.id_column1=table2.fk_id1 where table1.id_column1=1;

或者

SELECT id_column2,surname_column,fk_id1,name_column as name FROM table1 , table2 where table1.id_column1=table2.fk_id1 and table1.id_column1=1;

如果您希望得到以下格式的结果:

------------------------------------------------
|id_column2 | surname_column | fk_id1| name    |
------------------------------------------------
|      111  | my_surname1    | 1     |my_name1 |
于 2013-02-01T10:58:48.723 回答