使用sql从三个表中选择结果

时间:2013-02-05 16:36:05

标签: sql select multiple-tables

我想从三张桌子得到一个结果。我不知道如何编写SQL查询。请帮帮我。

"I want to display Name,Username and Product_Name where Id=007"

table "register"

Name  Username  Id
Arj   arjun     007
xyz   abcd      008
abcd  asdf      007

table "products"

Product_Id   Product_Name   Price
101           Clothes        200
102           Games          100

table "purchase"     //products.Product_Id=purchase.Item

Username   item    Id
arjun      102     007
abcd       101     008
asdf       102     007

3 个答案:

答案 0 :(得分:0)

尝试此查询:

SELECT a.Name,a.Username,c.Product_Name
FROM  register as a
JOIN purchase as b on a.Username=b.Username
JOIN products as c on b.item=c.Product_Id

它应该像这样工作。要阅读有关SQL连接的更多信息,请尝试:http://www.w3schools.com/sql/sql_join.asp

享受!

答案 1 :(得分:0)

SELECT Username, Id, Product_Name 
FROM register 
INNER JOIN purchase ON purchase.Id = register.Id 
INNER JOIN products ON purchase.Item = products.Product_Id
WHERE Id = '007'

作为旁注:您也不应将用户名保存在购买表中。

答案 2 :(得分:0)

应该是这样的

SELECT * FROM
register r
JOIN purchase p on p.username = r.username
JOIN products pr on pr.product_id = p.item

您可以修改此基本代码以包含特定列并添加where和order子句。