开发者

Append to MySQL Results if 1 column in NOT IN the results

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 开发者_Python百科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.


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


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'
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜