【发布时间】:2015-11-27 06:00:18
【问题描述】:
假设我有一个包含以下行的数据库:
id (auto_incremented) | id_person | first_name | last_name | phone | email
-----------------------------------------------------------------------------
1 | 12 | kevin | smith | | kevin@hotmail.com
2 | 12 | kevin | smith | 1-800-123-4567 |
3 | 33 | joe | jones | 1-800-765-4321 |
4 | 33 | joe | thompson | | joe@hotmail.com
5 | 33 | joe | thompson | | newjoe@hotmail.com
基于id_person,我想在单个查询中输出以下内容:
id | id_person | first_name | last_name | phone | email
-----------------------------------------------------------------------------
2 | 12 | kevin | smith | 1-800-123-4567 | kevin@hotmail.com
5 | 33 | joe | thompson | 1-800-765-4321 | newjoe@hotmail.com
所以基本上,我只想获取最新的行值,如果它们为空,则从第一行不为空的行中获取值。
我该怎么做?希望这是有道理的。
【问题讨论】:
-
清理数据比采用一些奇怪的数据检索方案要好。你能告诉我们为什么数据必须是这样的吗?
-
好吧,我有 2 张桌子。一个用于
people,另一个用于people_history。people_history表每人可以包含多于一行。我试图避免在两个表中使用完全相同的列,但这可能是我最好的选择... -
那么最好将两个表分开,当你想要最新的数据时使用
people。people_history表有重复数据是有原因的,就是存储一个人的历史数据。 -
@Populus 所说的,此外,您甚至可以通过在“当前数据”表上使用触发器来使历史记录表在某种程度上是自动的。
-
@daygloink : first_name 或 last_name 可以有空值吗?