0

mysqlクエリにはほとんど問題がありません。GROUP_CONCATにGROUP_CONCATのようなものが必要です。見る:

データベース設計:

ここに画像の説明を入力してください

SELECT cid, country, capital,
    GROUP_CONCAT(DISTINCT mid, '=',city SEPARATOR '|*|') AS data
FROM t1
    INNER JOIN t2 ON t2.c_id = t1.cid
    INNER JOIN t3 ON t2.c_id = t3.mid
WHERE t1.cid =1

戻る

[cid] => 1
[country] => France
[capital] => Paris
[data] => 1=Lyon|*|2=Chartres|*|3=Valence

しかし、私はこのクエリテーブルt4に参加したいと思っています(これを行う方法がわかりません)。出力が次のようになるとよいでしょう。

[cid] => 1
[country] => France
[capital] => Paris
[data] => 1=Lyon=|*|2=Chartres=Max#Alex#Frank|*|3=Valence=John

ps。t4.m_id = t3.mid

4

3 に答える 3

1

SQLでこれを実行する理由は正確にはわかりませんが、目的の結果を返すバージョンは次のとおりです。

SELECT  t1.cid,
  t1.country,
  t1.capital,
  GROUP_CONCAT(DISTINCT t34.mid,"=", t34.city, "=", t34.names ORDER BY t34.mid SEPARATOR "|*|" )AS data
FROM table1 t1
INNER JOIN table2 t2 
  ON t1.cid = t2.c_id
LEFT JOIN
(
  select t3.mid, t3.city,
    Coalesce(GROUP_CONCAT(DISTINCT t4.names SEPARATOR "#"), '') names
  from table3 t3
  left join table4 t4
    on t3.mid= t4.m_id
  group by t3.mid, t3.city
) t34
  ON t2.city_id = t34.mid
where t1.cid = 1
group by t1.cid, t1.country

SQL FiddlewithDemoを参照してください

結果:

| CID | COUNTRY | CAPITAL |                                                DATA |
---------------------------------------------------------------------------------
|   1 |  France |   Paris | 1=Lyon=|*|2=Chartes=Max#Alex#Frank|*|3=Valence=John |
于 2012-11-20T23:31:20.867 に答える
0

あなたのデータモデルは非常に混乱しています...つまりt2.city_id = t3s.mid...真剣に?

とにかく、ここに解決策があります:

SELECT cid, country, capital, GROUP_CONCAT(city_list SEPARATOR "|*|") AS data
FROM (
  SELECT mid, CONCAT(mid, "=", city, "=", COALESCE(names_list, "")) AS city_list
  FROM (
    SELECT m_id, GROUP_CONCAT(names SEPARATOR '#') AS names_list
    FROM t4
    GROUP BY m_id
  ) AS t4s
  RIGHT JOIN t3 ON t3.mid = t4s.m_id
) AS t3s
JOIN t2 ON t2.city_id = t3s.mid
JOIN t1 ON t1.cid = t2.c_id
GROUP BY cid

結果:

| CID | COUNTRY | CAPITAL |                                                 DATA |
----------------------------------------------------------------------------------
|   1 |  France |   Paris | 1=Lyon=|*|2=Chartres=Max#Alex#Frank|*|3=Valence=John |

SQLfiddleで表示

于 2012-11-20T23:27:31.667 に答える
0

テスト用のSQLフィドル。

select distinct cid,country,capital,
group_concat(distinct t3.mid,"=",city, '=', coalesce(names, '') separator "|*|") as data
from t1
inner join t2 on t2.c_id = t1.cid
inner join t3 on t2.city_id = t3.mid
left join (select m_id, group_concat(names separator '#') as names
           from t4
           group by m_id) t5 on t3.mid = t5.m_id
where t1.cid =1;
于 2012-11-20T23:34:56.970 に答える