sql选择关系多对多不能按预期工作

时间:2011-07-21 02:15:12

标签: mysql sql database select many-to-many

我有以下多对多关系表:

table product:
prd_cod (pk)
cat_cod (fk)
prd_nome 

table description_characteristic:
prd_cod(fk)
id_characteristic(fk)
description

table characteristic:
id_characteristic(pk)
name

我们假设cat_cod为1,我想显示这样的数据:

我在下面做了这个选择以解决我的问题:

select p.prd_cod,p.prd_name,c.name_characteristic,dc.description
from product p,description_characteristic dc, characteristic c
where p.prd_cod = dc.prd_cod and
dc.id_ccharacteristic = c.id_characteristic and
p.cat_cod = 1

但数据显示方式如下:

Prd_cod  Prd_name   name_characteristic  descript  
  1          pen        Color            pink      
  1          Pen        manufacturer     kingston  
  1          Pen        type                 brush
  1          Pen        weight               0.020

我想以这种方式显示结果:

Prd_cod  Prd_name   name_characteristic  descript  name_characteristic  descript
  1          pen        Color            pink      type                 brush
  2          Pen-drive  manufacturer     kingston  weight               0.020

我不能做一个选择来解决这个问题 拜托,我需要帮助 谢谢大家

2 个答案:

答案 0 :(得分:0)

Select VALUES YOU WANT
FROM CATEGORIES
LEFT JOIN product ON
product.cat_cod=CATEGORIES.cat_cod
LEFT JOIN description_characteristic ON
product.prd_cod = description_characteristic.prd_cod
LEFT JOIN characteristic ON
description_characteristic.id_characteristic=characteristic.id_characteristic
WHERE CATEGORIES.cat_cod = "1";

您需要输入tablename.column来选择存在于多个表中的字段。

(我假设你的类别表叫做CATEGORIES)

答案 1 :(得分:0)

此查询应解决您的问题,它将出现在同一列....

select 
    p.prd_cod
    , p.prd_name 
    , GROUP_CONCAT(c.name,dc.description) cd_list
from 
    product p
    ,description_characteristic dc
    ,characteristic c
where 
    p.prd_cod = dc.prd_cod and
    dc.id_characteristic = c.id_characteristic and
    p.cat_cod = 1