GROUP_CONCAT()是MySQL数据库提供的一个函数,通常跟GROUP BY一起用,具体可参考MySQL官方文挡:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat。语法: GROUP_CONCAT([DISTINCT]?expr?[,expr ...]?[ORDER?BY?{unsigne
GROUP_CONCAT()是MySQL数据库提供的一个函数,通常跟GROUP BY一起用,具体可参考MySQL官方文挡:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat。 语法:GROUP_CONCAT([DISTINCT]?expr?[,expr ...]?[ORDER?BY?{unsigned_integer | col_name | expr}?[ASC?|DESC]?[,col_name ...]]?[SEPARATOR str_val]) 1.例如: SELECT?student_id, GROUP_CONCAT(courses_id)?AS courses?FROM?student_courses?WHEREstudent_id=2?GROUP?BY?student_id;? +------------+---------+? | student_id | courses |? +------------+---------+? |?2? |?3,4,5?| +------------+---------+? 这 就不需要用php循环了 $row?=?$pdo->query("SELECT student_id, GROUP_CONCAT(courses_id) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id"); $result?=?explode(',',?$row['courses']);?2.当然分隔符还可以自定义,默认是以“,”作为分隔符,若要改为“|||”,则使用SEPARATOR来指定,例如:
SELECT?student_id, GROUP_CONCAT(courses_id SEPARATOR?'|||')?AS courses?FROM?student_coursesWHERE?student_id=2?GROUP?BY?student_id; +------------+---------+? | student_id | courses |? +------------+---------+? |?2 ?|?3|||4|||5?| +------------+---------+? 3.除此之外,还可以对这个组的值来进行排序再连接成字符串,例如按courses_id降序来排: SELECT?student_id, GROUP_CONCAT(courses_id?ORDER?BY?courses_id DESC)?AS courses?FROMstudent_courses?WHERE?student_id=2?GROUP?BY?student_id; +------------+---------+? | student_id | courses |? +------------+---------+? |?2?|?5,4,3?| +------------+---------+? 4.需要注意的:a.int字段的连接陷阱 当你用group_concat的时候请注意,连接起来的字段如果是int型,一定要转换成char再拼起来, 否则在你执行后(ExecuteScalar或者其它任何执行SQL返回结果的方法)返回的将不是一个逗号隔开的串, 而是byte[]。 该问题当你在SQLyog等一些工具中是体现不出来的,所以很难发现。 select group_concat(ipaddress) from t_ip 返回逗号隔开的串 select group_concat(id) from t_ip 返回byte[] select group_concat(CAST(id as char)) from t_dep 返回逗号隔开的串 select group_concat(Convert(id , char)) from t_dep 返回逗号隔开的串 附Cast,convert的用法: CAST(expr AS type), CONVERT(expr,type) , CONVERT(expr USING transcoding_name) CAST() 和CONVERT() 函数可用来获取一个类型的值,并产生另一个类型的值。 这个类型 可以是以下值其中的 一个: BINARY[(N)] CHAR[(N)] DATE DATETIME DECIMAL SIGNED [INTEGER] TIME UNSIGNED [INTEGER] b.长度陷阱 用了group_concat后,select里如果使用了limit是不起作用的. 用group_concat连接字段的时候是有长度限制的,并不是有多少连多少。但你可以设置一下。 使用group_concat_max_len系统变量,你可以设置允许的最大长度。 程序中进行这项操作的语法如下,其中 val 是一个无符号整数: SET [SESSION | GLOBAL] group_concat_max_len = val; 若已经设置了最大长度, 则结果被截至这个最大长度。 在SQLyog中执行 SET GLOBAL group_concat_max_len = 10 后,重新打开SQLyog,设置就会生效。
原文地址:Mysql函数GROUP_CONCAT, 感谢原作者分享。

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
