如果 1 列不在结果中,则附加到 MySQL 结果

发布于 2024-11-25 03:57:42 字数 432 浏览 1 评论 0原文

我想创建一个类似于

SELECT person, city FROM mytable 
UNION 
SELECT 'BOB', 'Chicago' IF 'BOB' NOT IN (SELECT person FROM mytable);

“如果结果中未返回“BOB”,我想将他附加到结果中并将他列为在芝加哥”的 MyQSL 查询。如果 BOB 确实出现在结果中,无论他的位置在哪里,我都不想将他添加为在芝加哥。

如果我完全匹配这些列,我就可以完成这项工作,但如果 BOB 被列为芝加哥以外的其他地方,我最终会得到多个结果。

SELECT person, city FROM mytable
UNION
SELECT 'BOB', 'Chicago'

但我不想在位置上进行匹配。只是这个人的名字。

I want to create a MyQSL Query similar to

SELECT person, city FROM mytable 
UNION 
SELECT 'BOB', 'Chicago' IF 'BOB' NOT IN (SELECT person FROM mytable);

If 'BOB' is not returned in the results, I want to append him to the results and list him as being in Chicago. If BOB does come back in the results, no matter what his location is, I do not want to append him as being in Chicago.

I can make this work if I exactly match the columns, but I will end up getting multiple results for BOB if he is listed as being somewhere other than Chicago.

SELECT person, city FROM mytable
UNION
SELECT 'BOB', 'Chicago'

but I do not want to match on the location. Just the person's name.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好听的两个字的网名 2024-12-02 03:57:42

这应该有效:

SELECT person, city FROM mytable 
UNION 
SELECT 'BOB', 'Chicago' from dual
 where NOT exists (SELECT person FROM mytable WHERE person = 'BOB');

更优化的版本,返回相同的结果

SELECT person, city FROM mytable WHERE person <> 'BOB'
UNION 
SELECT 'BOB', COALESCE((select city from mytable WHERE person = 'BOB'), 'Chicago') from dual

This should work:

SELECT person, city FROM mytable 
UNION 
SELECT 'BOB', 'Chicago' from dual
 where NOT exists (SELECT person FROM mytable WHERE person = 'BOB');

A more optimized version, that returns the same results

SELECT person, city FROM mytable WHERE person <> 'BOB'
UNION 
SELECT 'BOB', COALESCE((select city from mytable WHERE person = 'BOB'), 'Chicago') from dual
不回头走下去 2024-12-02 03:57:42

这是对原始查询的重写,应该可以工作:

SELECT person, city FROM mytable 
UNION 
SELECT 'BOB', 'Chicago' from dual where not exists (
  SELECT NULL FROM mytable where person = 'BOB'
);

Here's a rewrite of your original query that should work:

SELECT person, city FROM mytable 
UNION 
SELECT 'BOB', 'Chicago' from dual where not exists (
  SELECT NULL FROM mytable where person = 'BOB'
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文