了解mysql concat()函數


 

concat(arg1,arg2,....):將形參對應字段的值組合成一個字符串

假設:現在有一張學生表(test_user)

將這三個字段組合成一個字符串作為第四個字段

select test_user.*,
    concat(test_user.id,test_user.`name`,test_user.sex) as introduction
    from 
        test_user 
    GROUP BY `name`;

但是查詢出來的數據沒有分割符,可以在concat中加入常量

select test_user.*,
    concat(test_user.id,',',test_user.`name`,',',test_user.sex) as introduction
    from 
        test_user 
    GROUP BY `name`;

這樣寫如果分隔符都一樣,又要一直加,那不是很麻煩。

mysql提供另一個函數concat_ws(separator,arg1,arg2,.....),第一個參數為分隔符,第二個以后的參數為字段名

select 
    u.*,
    concat(u.id,',',u.`name`,',',u.sex) as introduction,
    CONCAT_WS('.',u.id,u.`name`,u.sex) as xinxi
  from test_user u GROUP BY u.`name`;

這些只是對單條記錄數據的拼接。

 

現在多了張課程表(test_subject)

想查詢每個學生的課程有哪些

select * from test_user LEFT JOIN test_subject on test_user.id = test_subject.user_id;

但是這樣看起來不夠直觀。那就干脆先按名稱分組。

select 
  *
from
  test_user LEFT JOIN test_subject
on test_user.id = test_subject.user_id
GROUP BY test_user.`name`;

但是分完組之后,課程只剩下一個了,沒有達到預期的要求,

mysql提供一個函數GROUP_CONCAT(arg1),內部的形參在分組時,則在arg1字段中將屬於該分組的值字段進行拼接,拼接順序會被order by影響

select 
  test_user.*,
  GROUP_CONCAT(test_subject.`subject`) as `subject`
from
  test_user LEFT JOIN test_subject
on
  test_user.id = test_subject.user_id
GROUP BY
  test_user.`name`;

完成。清晰明了的顯示各個學生所有的科目。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM