【发布时间】: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