mysql - 从值内的不同列或表调用变量

标签 mysql

我的数据库中有一个名为 ProductInfo 的表。此表包含特定产品的文字说明。只是一个名为 description 的文本字段,图片 url 等。

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

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

所以.. 在我的 ProductInfo 表中,我有一个名为“Widget”的条目,它有一个描述。我希望能够执行以下操作:

This widget is the best widget money can buy. If you live in the ($city1, $city2, $city3) area then you simply must by this widget from ($company_name). ($company_name) specializes in providing ($service1) for clients living in the ($city 4), ($state) areas.

任何人都可以提供一些关于我如何能够做到这一点的见解。我猜它会将变量嵌套在其他变量中,但我不确定。

提前致谢。

最佳答案

Dax,我没有太多信息可以继续,但这里有一个查询可以组合来自三个表的字段:

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 子句。

祝你好运。

关于mysql - 从值内的不同列或表调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5793297/

相关文章:

MySQL 使用 openSSL/企业加密

MySQL 查询根据另一列的值将 ialue 插入到列中

mysql - Pharo Smalltalk 和 mySql

c# - 如何从mysql数据库显示图像到datagridview

mysql - SQL : Return only the most recent activity per customer

php - 关于mysql_real_escape_string的问题

mysql - HSQL 和按位运算?

更改表的 SQL 查询

php - 当 PHP 表单上的复选框未选中时删除多个 MySQL 行

mysql - 如何在 MySQL 数据库修订安全(可信时间戳)中签署数据?