【问题标题】:MySQL - Similar headings - multiple tablesMySQL - 类似的标题 - 多个表
【发布时间】:2015-08-27 10:50:11
【问题描述】:

我有 2 个表,一个包含主要信息,第二个表包含相同的字段和附加信息。第二个表将包含在查询时应覆盖第一个表的数据。字段更大,我只是将它们缩短显示在这里。

第一个表(产品):

+----+--------------+--------------+---------------+--------------------------+
| id | manufacturer | product_name | product_title |      product_description |
+----+--------------+--------------+---------------+--------------------------+
|  1 |     testingA |     productA | productTitleA | main product description |
|  2 |     testingA |     productB | productTitleB | main product description |
|  3 |     testingA |     productC | productTitleC | main product description |
+----+--------------+--------------+---------------+--------------------------+

第二个表(products_secondary)

+----+------------+--------------+--------------+---------------+----------------------+---------+
| id | product_id | manufacturer | product_name | product_title |  product_description | context |
+----+------------+--------------+--------------+---------------+----------------------+---------+
|  1 |          1 |       (null) |       (null) |        (null) | new description here |    test |
+----+------------+--------------+--------------+---------------+----------------------+---------+

我的目标是从第二个表中选择 context = text 的值

预期结果:

+----+--------------+--------------+---------------+--------------------------+
| id | manufacturer | product_name | product_title |      product_description |
+----+--------------+--------------+---------------+--------------------------+
|  1 |     testingA |     productA | productTitleA | new description here     |
|  2 |     testingA |     productB | productTitleB | main product description |
|  3 |     testingA |     productC | productTitleC | main product description |
+----+--------------+--------------+---------------+--------------------------+

我知道有效的查询如下:

SELECT IFNULL(`products_secondary`.`product_description` , `products`.`product_description`) AS `product_description`
来自`产品`
LEFT JOIN `products_secondary` ON `products_secondary`.`product_id` = `products`.`id` AND `products_secondary`.`context` = 'test'

我确信有一种比为每个字段提供 IFNULL() 更简单的方法。这是一个 SQL Fiddle:http://sqlfiddle.com/#!9/6985b/1

谢谢。

【问题讨论】:

  • 这是一个糟糕的数据库设计。为什么将表 1 中的所有列都放在表 2 中,但是将它们全部设为 NULL 就更没有意义了
  • @RiggsFolly 看起来第一个表是默认值,第二个表覆盖了默认值。一个更常见的应用程序是翻译表,当没有翻译时有一个默认表。
  • 我认为没有比大量IFNULL 测试更简单的方法了。对不起。
  • 在当前设计下,ifnulls 或等效的 case 语句看起来是唯一的选择。

标签: mysql


【解决方案1】:

使用这个查询

SELECT a.id, a.manufacturer, a.product_name, a.product_title, IF(b.context IS NOT NULL, b.product_description, a.product_description) as product_description
FROM
    products a
    LEFT OUTER JOIN products_secondary b ON a.id=b.product_id

【讨论】:

  • 它可以在这个特定的例子中工作,但请注意这是一个默认表的例子,即如果主表中的字段没有值,则从默认值中获取。不幸的是,对于一般情况,正确的做法是 ifnulls。
猜你喜欢
  • 1970-01-01
  • 2012-10-30
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
相关资源
最近更新 更多