2016-03-23 9 views
0

私はsqlzooの問題を解決しようとしています。国名、大陸、面積、人口、gdpを含む表が用意されています。問題は、名前と大陸を示すことですが、ユーラシアをヨーロッパとアジアに代えます。北米、南米、カリブ海諸国の各国の代理アメリカ -mysqlで "like"と "in"を使用できないのですか?

select name, case 
when continent in ('europe', 'asia') then 'Eurasia' 
when continent in ('north america', 'south america', 'caribbean') then 'America' else continent end as continent 
from world where name like 'A%' or name like 'B%' 

が、次のコードを使用したい場合は、それが動作しない:私は次のクエリを使用していた場合、それが正常に動作しているAまたはB で始まる国を表示

select name, case 
when continent in ('europe', 'asia') then 'Eurasia' 
when continent in ('north america', 'south america', 'caribbean') then 'America' else continent end as continent 
from world where name like in ('A%', 'B%') 

唯一の違いは、名前を1つの括弧で囲んでいることです。 "like"を "in"で使うことはできませんか?

+1

を。 –

答えて

1

いいえ、できません。 LIKEINは異なる演算子です。あなたは彼らが望むようにそれらを組み合わせることはできません。

0

LIKEは、定数(文字列、日付、数字)でのみ動作します。

あなたが正規表現でやりたいことができます。

where name regexp '^[AB].*$' 

注:正規表現は、文字列内の任意の場所に一致するものを探しので、あなたがname regexp '^[AB]'にこれを簡素化することができます。しかし、私はセマンティクスをlikeと同じにしておきたいので、正規表現をSQLで使用すると、文字列全体に強制的に一致させます。

0

あなたはそのような両者を混在させることはできませんが、(それはあなたがやっている何のために適切であるかどう一時テーブルを)あなたは、テーブルの中に、様々なLIKEパターンを置くことができ、その後、そのオフJOIN

SELECT 
    name, 
    case 
     when continent in ('europe', 'asia') then 'Eurasia' 
     when continent in ('north america', 'south america', 'caribbean') then 'America' 
     else continent 
    end as continent 
FROM 
    World W 
INNER JOIN Name_Patterns NP ON W.name LIKE NP.name_pattern 

Name_Patternsは、検索するパターンごとに1つの列が必要です。それらがそれぞれの呼び出しごとに変更された場合、その場で構築された一時テーブルがおそらく適切です。これらが事前に構成されている場合は、実際の表が理にかなっています。

あなたのパターンは、1つまたは2つに限定されている場合、あなたはおそらくWHERE句増築方がいいでしょう:いいえ、することはできません

SELECT 
    name, 
    case 
     when continent in ('europe', 'asia') then 'Eurasia' 
     when continent in ('north america', 'south america', 'caribbean') then 'America' 
     else continent 
    end as continent 
FROM 
    World W 
WHERE 
    (
     W.name LIKE 'A%' OR 
     W.name LIKE 'B%' 
    ) 
関連する問題