如何从mysql中的parent_id获取值?

时间:2012-06-25 02:42:30

标签: php mysql

我有一个示例数据

game(id, name)
      1 | Avatar
      2 | Angry Bids
brand(id, parent_id, name)
      1 | 0 | Apple
      2 | 0 | Samsung
      3 | 1 | Iphone 4
      4 | 2 | Galaxy Tab
game_brand(game_id, brand_id)
              1   | 4
              2   | 3

并查询:

SELECT game.name, 
       game_brand.brand_id, 
       (SELECT brand.parent_id 
        FROM   brand AS brand 
        WHERE  brand.brand_id = game_brand.brand_id) AS brand_father_id 
FROM   game AS game 
       LEFT JOIN game_brand AS game_brand 
              ON game_brand.game_id = game.id 
WHERE  game.id = 2 

AND结果:

name       | brand_id |    brand_father_id
Angry Bids |    3     |       1

如何从brand_idbrand_father_id获取值,例如:

game       | brand    | brand parent
Angry Bids | Iphone 4 | Apple 

3 个答案:

答案 0 :(得分:1)

SELECT game.name, child.name AS brand_name, parent.name AS brand_father_name
FROM game_brand INNER JOIN game ON game_brand.game_id = game.id
INNER JOIN brand AS child ON game_brand.brand_id = child.id
INNER JOIN brand AS parent ON child.parent_id = parent.id
WHERE game.id = 2

<强>已更新

SELECT game.name, child.name AS brand_name, (SELECT name FROM brand AS parent WHERE child.parent_id = parent.id) AS brand_father_name
FROM game_brand INNER JOIN game ON game_brand.game_id = game.id
INNER JOIN brand AS child ON game_brand.brand_id = child.id
WHERE game.id = 2

再次更新

又重新刚才注意到OP不仅想要父亲的名字,还想要孩子的名字(而不是他们的ids),所以更新了他们......

答案 1 :(得分:0)

尝试这个

SELECT
  game.name,    
  brand.name          AS brand_father_name,
  brndName.name       AS brand_name
FROM game AS game
  LEFT JOIN game_brand AS game_brand
    ON game_brand.game_id = game.id
  LEFT JOIN brand AS brand
    ON brand.id = game_brand.brand_id
  LEFT JOIN brand AS brndName
    ON brndName.id = brand.parent_id
WHERE game.id = 2

答案 2 :(得分:0)

显然,如果您的模型和查询的约束被视为纯粹抽象,Nikola的答案就是现实。但是对于那些发现这个问题的人,因为他们有类似的模型以及类似的目标,这里有一个不同的方法:

通过将品牌表分成两个单独的表来删除品牌层次结构中不需要的约束:

brand(id, manufacturer_id, name)
      1 | 1 | Iphone 4
      2 | 2 | Galaxy Tab

manufacturer(id, name)
      1 | Apple
      2 | Samsung

这是基于我从样本数据模型中推断的某些假设:

  1. 游戏永远不会与“母品牌”直接相关
  2. “儿童品牌”永远不会成为“母品牌”
  3. 如果以上情况属实,则manufacturer表更合适/规范化,并将查询减少为:

    SELECT 
         game.name AS game, 
         brand.name AS brand, 
         manufacturer.name AS manufacturer
    FROM game 
         JOIN game_brand ON (game.id = game_id)
         JOIN brand ON (brand_id = brand.id)
         JOIN manufacturer ON (brand.manufacturer_id = manufacturer.id)
    

    以上内容将返回与与制造商有关系的品牌有关系的所有游戏。要获得所有游戏,即使他们只拥有一个品牌,您也可以使用左连接至少进行最后一次加入。