如何从sql中的3个表中选择数据?

时间:2011-09-04 21:28:18

标签: sql database

我有3张桌子:

create table user (
    user_id integer primary key autoincrement,
    username string not null,
    email string not null,
    pw_hash string not null
);


create table product (
    product_id integer primary key autoincrement,
    productname string not null,
    productdescription string not null,
);

create product_review (
    product_id integer,
    user_id integer,
    review,
);

现在,我想显示来自user_id = 1的所有评论。对此的简单查询将是     从product_review中选择*,其中user_id = 1

但是,我希望将数据列为 - >

username  productname review
John      iPad3       Super awesome
John      SonyVaio    Even more awesome

1 个答案:

答案 0 :(得分:4)

试试这个:

SELECT username, productname, review
  FROM user a INNER JOIN product_review pr
    ON a.user_id = pr.user_id INNER JOIN product p
    ON p.product_id = pr.product_id
 WHERE a.user_id = 1