簡體   English   中英

用GROUP_CONCAT查詢

[英]Query with GROUP_CONCAT

我對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

我不確定為什么要在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 Fiddle

結果:

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

您的數據模型非常令人困惑...我的意思是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上查看

SQL Fiddle進行測試。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM