从表中选择行并用另一列中的字段替换字段(如果存在)
我正在尝试构建一个执行以下操作的 PostgreSQL 查询,但到目前为止我的努力都是徒劳的。
问题: 有两个表:A 和 B。我想从表 A 中选择所有列(具有列:id、name、description),并将“A.name”列替换为“B.title”列的值来自表 B(具有列:id、table_A_id 标题、langcode),其中 B.table_A_id 为 5,B.langcode 为“nl”(如果有任何行)。
我的尝试:
SELECT A.name,
case when exists(select title from B where table_A_id = 5 and langcode= 'nl')
then B.title
else A.name
END
FROM A, B
WHERE A.id = 5 and B.table_A_id = 5 and B.langcode = 'nl'
-- second try:
SELECT COALESCE(B.title, A.name) as name
from A, B
where A.id = 5 and B.table_A_id = 5 and exists(select title from B where table_A_id = 5 and langcode= 'nl')
我尝试使用 CASE 和 COALESCE() 但由于我对这两个概念缺乏经验而失败。
提前致谢。
I'm trying construct a PostgreSQL query that does the following but so far my efforts have been in vain.
Problem:
There are two tables: A and B. I'd like to select all columns from table A (having columns: id, name, description) and substitute the "A.name" column with the value of the column "B.title" from table B (having columns: id, table_A_id title, langcode) where B.table_A_id is 5 and B.langcode is "nl" (if there are any rows).
My attempts:
SELECT A.name,
case when exists(select title from B where table_A_id = 5 and langcode= 'nl')
then B.title
else A.name
END
FROM A, B
WHERE A.id = 5 and B.table_A_id = 5 and B.langcode = 'nl'
-- second try:
SELECT COALESCE(B.title, A.name) as name
from A, B
where A.id = 5 and B.table_A_id = 5 and exists(select title from B where table_A_id = 5 and langcode= 'nl')
I've tried using a CASE and COALESCE() but failed due to my inexperience with both concepts.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我敢打赌,araqnid 就是您正在寻找的答案。
但是,如果您想强制为每个原始匹配
A
行返回不超过一行,您可能更愿意执行子选择而不是 LEFT JOIN。例如:我在这里使用“max”来选择任意值(如果有多个值)。您可以使用“分钟”或任何您认为适合您的情况的值。
也许这比 LEFT JOIN 更容易理解,但是(除了两者不完全等同)JOIN 的性能会比 N 个子选择更好(N 越大越好)。
不管怎样,从学习的角度来看,两者都了解一下还是有好处的。
araqnid's is the answer you are looking for, I bet.
But if you want to enforce that no more than one row is returned for each original matching
A
row, you might prefer to do a subselect instead of a LEFT JOIN. For example:I use "max" here to select an arbitrary value, in the event there is more than one. You can use "min" or whatever you consider appropiate in your case.
Perhaps this is more easy to understand than the LEFT JOIN, but (apart from the two being not exactly equivalent) a JOIN will perform better than N subselects (much better is N is large).
Anyway, from a learning point of view, it's good to understand both.
好的,我不确定如何连接您的表,但是类似这样的方法应该可以完成这项工作:
另一种方法是使用 COALESCE() 函数:
Ok, I'm not sure how your tables have to be joined, but something like this should do the job:
Another way to do it would be to use the COALESCE() function:
试试这个
Try this