我有两个表Category
和Product_Category
。这是我的Category
表:
CREATE TABLE Category (
id BIGINT PRIMARY KEY,
category_name VARCHAR,
category_description TEXT,
image_path VARCHAR
)
CREATE TABLE Product_Category (
product_id integer,
category_id integer,
description TEXT,
numberOfProduct integer,
image TEXT,
price integer,
PRIMARY KEY (product_id, category_id)
)
我想创建一个查询以在Product_Category
表中找到我的category_name
的所有Category
。另外,我想查询特定的Product_Category
和特定的Category
。
答案 0 :(得分:0)
您可以将两个表连接为:
SELECT c.category_name, p.product_id, p.category_id, p.description, p.numberOfProduct, p.image, p.price FROM category c
LEFT JOIN Product_Category p ON c.id=p.category_id
答案 1 :(得分:0)
要找到类别名称的所有Product_Category,可以使用join:
select pc.* from category as cn inner join Product_Category as pc on
pc.category_id = cn.id where cn.category_name = "name_of_category"
答案 2 :(得分:0)
首先,我建议您为相关列使用相同的数据类型。
在“类别”表中,您将ID用作 BIGINT ,在 Product_Category 表
的 category_id 列中使用了相同的ID。CREATE TABLE Category (
id BIGINT PRIMARY KEY, // -----> BIGINT
category_name VARCHAR,
category_description TEXT,
image_path VARCHAR
)
CREATE TABLE Product_Category (
product_id integer,
category_id integer, // -------> here should also be BIGINT
description TEXT,
numberOfProduct integer,
image TEXT,
price integer,
PRIMARY KEY (product_id, category_id)
)
SELECT
PC.*
FROM category AS C
INNER JOIN Product_Category AS PC
ON PC.category_id = C.id
WHERE C.category_name = "value" ----> **Here goes the value of the category you want to search**
注意::C.category_name =“值”,该值必须完全相同才能获得结果。