如何从mysql数据库中查询指定字段且符合条件的数据 ,然后拼接成json字符串,最后导出json文件

SELECT CONCAT("{'name':'",IFNULL(Name,''),"',","'sex':'",IFNULL(Sex,''),"',","'age':'",IFNULL(Age,''),"',",
"'phone':'",IFNULL(Phone,''),"',","'birthday':'",IFNULL(Birthday,''),"'","},") from Student  where Status=9
 INTO OUTFILE '/var/lib/mysql-files/query_student.json';

在MySQL中CONCAT函数有一个特点就是有一个值为NULL那么不管第二个字符有多少内容都返回为空了,所以我们使用IFNULL来取出想取出的数据。
如果我们要对取出的数据进行处理,如需要将男生定义为1,女生定义为2,我们可以使用case when来处理数据:

SELECT CONCAT("{'name':'",IFNULL(Name,''),"',","'sex':'",IFNULL(case when Sex LIKE "%男%" then 1 when Sex LIKE "%女%" then 2 end,''),"',","'age':'",IFNULL(Age,''),"',",
"'phone':'",IFNULL(Phone,''),"',","'birthday':'",IFNULL(Birthday,''),"'","},") from Student  where Status=9
 INTO OUTFILE '/var/lib/mysql-files/query_student.json';

这里我们使用LIKE来判断是男生还是女生,因为有的数据库存的是“男”“女”,有的数据库存的是“男生”“女生”等。
如果我们取出的名字字段有转义字符,那么需要我们处理转义字符:

SELECT CONCAT("{'name':'",IFNULL(REPLACE(Name,'\'','\\\''),''),"',","'sex':'",IFNULL(case when Sex LIKE "%男%" then 1 when Sex LIKE "%女%" then 2 end,''),"',","'age':'",IFNULL(Age,''),"',",
"'phone':'",IFNULL(Phone,''),"',","'birthday':'",IFNULL(Birthday,''),"'","},") from Student  where Status=9
 INTO OUTFILE '/var/lib/mysql-files/query_student.json';

在这里我们使用replace对名字中的转义字符进行处理。
如果取出的数据有重复,且我们判定重复的条件为:几个字段相同才判定为相同,而distinct只能处理一个字段重复的情况,这时我们使用group by来进行处理:

SELECT CONCAT("{'name':'",IFNULL(REPLACE(Name,'\'','\\\''),''),"',","'sex':'",IFNULL(case when Sex LIKE "%男%" then 1 when Sex LIKE "%女%" then 2 end,''),"',","'age':'",IFNULL(Age,''),"',",
"'phone':'",IFNULL(Phone,''),"',","'birthday':'",IFNULL(Birthday,''),"'","},") from Student  where Status=9 GROUP BY name,phone
 INTO OUTFILE '/var/lib/mysql-files/query_student.json';

这里我们通过姓名和电话号码两个字段判定是否是相同数据。

你可能感兴趣的:(数据库)