我有两张桌子:
表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;
答案 0 :(得分: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;
答案 1 :(得分: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。
答案 2 :(得分: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 |