如何从两个表基于第一个表

如何从两个表基于第一个表

问题描述:

的列值获得行的信息,我有以下两个表:如何从两个表基于第一个表

表A

article_id | attribute_id 
1   | 5 
2   | 6 

表B

attribute_id | attribute_name 
5   | foo 
6   | bar 

我将如何获得相应的行如果我只知道文章ID?所以,如果我通过的article_id 1,我得到:

article_id | attribute_id | attribute_name 
1   | 5   | foo 

我知道我可以用两个单独的查询做,但不知道是否可以在一个做?我想过使用INNER JOIN ON,但article_id不在这两个表中?

感谢

可以肯定的,你可以(而且必须)使用INNER JOIN

SELECT TableA.article_id, TableB.* 
FROM TableA 
INNER JOIN TableB ON TableA.attribute_id = TableB.attribute_id 
WHERE TableA.article_id = 1 

SELECT部分让我们从第一个表中检索article_id,并从第二个各个领域。
INNSER JOIN子句从两个表中连接具有相同attribute_id的行。
WHERE条件让我们只在第一个表中选择​​的行。

+0

啊得到它的感谢! – Bob 2011-12-24 18:34:45

加入使用attribute_id

SELECT * FROM TableA A, TableB B where 
A.attribute_id = B.attribute_id 

select article_id, tablea.attribute_id,attribute_name 
    from tablea,tableb where  
    tablea.attribute_id=tableb.attribute_id 
    and article_id= :passedId 

使用天然JOIN - Wikipedia Entry

SELECT * 
FROM TableA NATURAL JOIN TableB 
WHERE article_id = 1