SQL如何查找非空列?
我有一个有很多列的表,假设我有列
A、B、C、D
中,任何一条记录中仅填充一列,其他列始终为 NULL。
我需要一个 select 语句来返回非空列的列。
我尝试过合并,但这返回一个值,而不是该值所属的列。
有人知道最简单的方法吗?
I have a table with lots of columns, say I have columns
A, B, C, D
in each of these columns, only one column in any one record will be filled and the others will always be NULL.
I need a select statement that will return the Column of the non null Column.
I've tried coalesce, but this return a value, not the column to which the value belongs to.
Anyone know the simplest way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试案例...
Try case...
每当您发现自己尝试使用多列集执行操作时,您的架构可能是错误的。
几乎可以肯定,将 A、B、C 和 D 分成单独表中的单独行,将它们绑定回原始表中的行并创建 JOIN 类型查询会更容易。
或者,如果只有一列非 NULL,我会选择两列:类型(A、B、C 或 D)和值。这样您就不会浪费每一行中的列,并且查询会变得更加容易(假设类型相同)。
但是,您可以使用
case
这样做:语法可能不完全正确,您需要查找它。这不是我通常做的事情,因为我认为这是一个坏主意(select 中的每行函数永远无法很好地扩展)。
Whenever you find yourself trying to do things with multi-column sets, you've probably got your schema wrong.
It would almost certainly be easier to separate A, B, C and D into separate rows in a separate table, tie them back to the row in the original table and create a
JOIN
-type query.Alternatively, if only one is ever non-NULL, I would opt for two columns, type (A, B, C or D) and value. Then you're not wasting the columns in every row, and the queries are immeasurably easier (assuming the types are the same).
However, you can do it this way with
case
:The syntax may not be exactly correct, you'll need to look it up. IIt's not something I usually do since I consider it a bad idea (per-row functions in select never scale well).
不漂亮,但这就是你想要的:
Not pretty but this does what you want:
我会重新设计。事实证明,以这种方式存储数据而不是在相关表中存储数据几乎是一个坏主意。
在相关表中您可以更方便地查询信息。您还可以更轻松地对数据施加约束,仅允许一条记录,因此您可能会获得更好的数据完整性。
更少的表并不一定意味着关系数据库中的访问速度更快或设计更好。设计合理且索引良好的相关表通常相当不错。虽然您可能认为永远不需要第五列,但业务规则发生了变化,而且我看到了许多人们认为不需要扩展的东西,结果却需要可扩展性。
I would redesign. It almost alawys turns out to be a bad idea to store data this way instead of in a related table.
In a related table you can more easily query the information. You can also more easily put a constraint on the data that only one record is allowed, so you will will probably have better data integrity.
Fewer tables does not necessarily mean faster access or better design in relational databases. Porperly designed and indexed related tables are generally quite good. And while you may think you won't ever need a fifth column, business rules change and I've seen many things that people thought wouldn't need expansion that turned out to need the scalibilty.