2011-04-26 55 views
2

我的数据库中有一个名为ProductInfo的表。此表格包含特定产品的文字说明。只是一个文本字段description,图片url等从值中调用不同列或表的变量

我有另一个表Locations。在这张表中,我有公司名称,城市名称(纽约,波士顿,奥马哈等)

我想要做的就是将Locations表中的变量插入ProductInfo中描述的文本字段表。

所以..在我的ProductInfo表中,我有一个名为“Widget”的条目,它有一个描述。我想能够做到以下几点:

这个小工具是金钱可以买到的最好的部件。如果你住在($city1,$city2,$city3)区域,那么你只需从这个小部件($company_name)中获得。 ($company_name)专门为生活在($city 4),($state)地区的客户提供($service1)。

任何人都可以提供一些见解,如何我可以做到这一点。我想这将嵌套在其他变量的变量,但我不知道。

在此先感谢。

+0

对此的解决方案很大程度上取决于您需要的灵活性。只需将一个记录中的连接值插入另一个记录很容易,并且可以将来自多个记录的值连接在一起并执行相同操作。在不使用存储过程(或外部脚本)的情况下执行操作可能会非常棘手。你能发表一些确切的表格内容的例子(表明你正在使用的关系)吗? – Simon 2011-04-26 16:30:20

+0

你使用php吗? – Johan 2011-04-26 17:32:15

+0

@Johan,我认为Dax正在寻找一个纯粹的SQL答案 – edgerunner 2011-04-27 11:43:46

回答

0

达克斯,我很少有信息去,但这里有一个查询将从三个表合并字段:

Location 
    id integer not null autoincrement primary key 
    company_id integer not null 
    city varchar not null 
    FOREIGN KEY company_id REFERENCES company.id ON DELETE CASCADE ON UPDATE CASCADE 

Company 
    id integer not null autoincrement primary key 
    companyname varchar not null 
    service varchar not null 
    city varchar not null 
    state varchar not null 
    ....other fields... 

ProductInfo 
    id integer not null autoincrement primary key 
    company_id integer not null 
    productname varchar .... 
    FOREIGN KEY company_id REFERENCES company.id ON DELETE CASCADE ON UPDATE CASCADE 

此查询会产生您所需要的信息。

SELECT group_concat(DISTINCT l.city ORDER BY l.city SEPARATOR ', ') AS city 
    , c.companyname 
    , c.service 
    , c.city 
    , c.state 
FROM location l 
INNER JOIN productInfo pi ON (pi.company_id = l.company_id) 
INNER JOIN company c ON (pi.company_id = c.id) 
WHERE pi.id = 589 
GROUP BY pi.id 

主要的窍门是GROUP_CONCAT完成,
看到:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
如果使用group_concat还必须包括一个group by条款。

祝你好运。