7

私はたくさん検索しましたが、私の問題に対する適切な解決策が見つかりませんでした。

私は何をしたいですか?

MySQL に 2 つのテーブルがあります: - Country - Currency (CountryCurrency を介して結合します --> 多対多の関係のため)

実際の例については、http ://sqlfiddle.com/#!2/317d3/8/0 を参照してください。

結合を使用して両方のテーブルをリンクしたいのですが、国ごとに 1 つの行だけを表示したい (国によっては複数の通貨があるため、それが最初の問題でした)。

group_concat 関数を見つけました:

SELECT country.Name, country.ISOCode_2, group_concat(currency.name) AS currency
FROM country
INNER JOIN countryCurrency ON country.country_id = countryCurrency.country_id
INNER JOIN currency ON currency.currency_id = countryCurrency.currency_id
GROUP BY country.name

これにより、次の結果が得られます。

NAME            ISOCODE_2   CURRENCY

Afghanistan AF          Afghani
Åland Islands   AX          Euro
Albania         AL          Lek
Algeria         DZ          Algerian Dinar
American Samoa  AS          US Dollar,Kwanza,East Caribbean Dollar

しかし、私が今欲しいのは、通貨を異なる列 (通貨 1、通貨 2、...) に分割することです。私はすでに MAKE_SET() のような関数を試しましたが、これはうまくいきません。

4

3 に答える 3

6

でこれを行うことができますsubstring_index()。次のクエリは、あなたのものをサブクエリとして使用し、このロジックを適用します。

select Name, ISOCode_2,
       substring_index(currencies, ',', 1) as Currency1,
       (case when numc >= 2 then substring_index(substring_index(currencies, ',', 2), ',', -1) end) as Currency2,
       (case when numc >= 3 then substring_index(substring_index(currencies, ',', 3), ',', -1) end)  as Currency3,
       (case when numc >= 4 then substring_index(substring_index(currencies, ',', 4), ',', -1) end)  as Currency4,
       (case when numc >= 5 then substring_index(substring_index(currencies, ',', 5), ',', -1) end)  as Currency5,
       (case when numc >= 6 then substring_index(substring_index(currencies, ',', 6), ',', -1) end)  as Currency6,
       (case when numc >= 7 then substring_index(substring_index(currencies, ',', 7), ',', -1) end)  as Currency7,
       (case when numc >= 8 then substring_index(substring_index(currencies, ',', 8), ',', -1) end)  as Currency8
from (SELECT country.Name, country.ISOCode_2, group_concat(currency.name) AS currencies,
             count(*) as numc
      FROM country
      INNER JOIN countryCurrency ON country.country_id = countryCurrency.country_id
      INNER JOIN currency ON currency.currency_id = countryCurrency.currency_id
      GROUP BY country.name
     ) t

この式substring_index(currencies, ',' 2)は、2 番目までの通貨のリストを取得します。アメリカ領ソモアの場合、'US Dollar,Kwanza'. -1引数として を使用した次の呼び出しは、リストの最後の要素 ('Kwanza'の 2 番目の要素である ) を取りますcurrencies

また、SQL クエリは明確に定義された一連の列を返すことにも注意してください。クエリに可変数の列を含めることはできません (prepareステートメントを介して動的 SQL を使用している場合を除く)。

于 2013-07-24T14:17:36.697 に答える
-2

Ypu は動的 SQL を使用できますが、プロシージャーを使用する必要があります

于 2013-07-24T14:20:04.217 に答える