如何从SQL中的两个不同表中选择值

时间:2016-07-21 06:26:23

标签: php mysql database

我的SQL Server数据库中有两个表。第一个是catgeories,第二个是产品。两个表中都有列categories_id。

这是我的分类表:

+----+----------+----------+
| id | category | parent   |
+----+----------+----------+
|  1 | BOY      | 0        |
|  2 | GIRL     | 0        |
|  3 | SHIRT    | 1        |
|  4 | SKIRT    | 2        |
|  5 | JACKET   | 1        |
+----+----------+----------+

表:产品

+-------+--------------+----------------------+
| id    | title        |PRICE | Categories    |
+-------+--------------+------+---------------+
| 1     | RED SHIRT    | 300  |     3         |
| 2     | blue SKIRT   | 500  |     4         |  
| 3     | jeans jacket | 500  |     3         |           
+-------+--------------+------+-----+---------+

现在我想从Products表中为BOY等特定类别选择值。

5 个答案:

答案 0 :(得分:1)

试试这个:

SELECT pr.id,pr.title,pr.price from products AS pr
INNER JOIN CATEGORIES AS cat ON  cat.id=pr.Categories
WHERE cat.category='Boy';

答案 1 :(得分:0)

 SELECT products.* FROM products INNER JOIN categories ON products.categories = categories.id WHERE categories.category LIKE '%BOY%';

使用此查询..

答案 2 :(得分:0)

无论

SELECT * FROM tproducts WHERE categories = 1

SELECT * FROM tproducts
JOIN tcategories ON tcategories.id = tproducts.categories WHERE tcategories.category = 'BOY'

我不知道你的表名,所以我只使用了tproducts和tcategories

答案 3 :(得分:0)

为此使用连接查询示例:

select *(or you can get any column as you write name) from table1 join table2 on table1.id=table2.id where table1.category='BOY';     

答案 4 :(得分:0)

产品(表格)中的类别(字段)中没有男孩(1)ID

SELECT * FROM CATEGORIES 内部联合产品 ON CATEGORIES.id = PRODUCTS.Categories 在哪里CATEGORIES.category =' BOY'