Mysql:如何从id获取其他表库中的值

时间:2012-09-09 13:34:25

标签: mysql

假设我的数据库中有3个表

Table:Category   
   category_id

Table:container   
   container_id
   category_id

Table:products

   container_id
   product_id

如何根据category_id获取所有product_id?

例如,我在上面的表格中有这些数据:

Table: category
    sour
    sweet
    Bitter


Table: container
    bottled
    sachet

Table: product
    sugar
    vinegar
    cocoa

如何获得类别(tb_product)甜蜜的所有产品(tb_category

3 个答案:

答案 0 :(得分:1)

您可以使用INNER JOIN来解决问题。

SELECT  a.*
FROM    products a
        INNER JOIN container b
            on a.container_id = b.container_ID
        INNER JOIN Category c
            ON b.category_ID = c.categoryID
WHERE   c.categoryName = 'sweete'

如您所见,我假设Category表包含category_ID列和categoryName列。因此,在上面的示例中,我使用类别名称来搜索属于特定类别的所有产品。

答案 1 :(得分:0)

select p.*
from Category c
join container c2 on c2.category_id = c.category_id
join product p on p.container_id = c2.container_id
where c.name = 'sweet';

请注意查询中表格的顺序(其执行速度应快于其他答案!)

答案 2 :(得分:0)

你可以像这样使用内连接:

SELECT a.product_id FROM products AS a INNER JOIN  container AS b on a.container_id = b.container_Id INNER JOIN Category AS c on  b.category_Id = c.category_id where c.category_id = 'new'
相关问题