select * from goods; +------+------+ | id| price| +------+------+ |1 | 10| |1 | 20| |1 | 20| |2 | 20| |3 | 200 | |3 | 500 | +------+------+ 6 rows in set (0.00 sec)
以id分组,把price字段的值在同一行打印出来,逗号分隔(默认)
select id, group_concat(price) from goods group by id; +------+--------------------+ | id| group_concat(price) | +------+--------------------+ |1 | 10,20,20| |2 | 20 | |3 | 200,500| +------+--------------------+ 3 rows in set (0.00 sec)
以id分组,把price字段去重打印在一行,逗号分隔
select id,group_concat(distinct price) from goods group by id; +------+-----------------------------+ | id| group_concat(distinct price) | +------+-----------------------------+ |1 | 10,20| |2 | 20 | |3 | 200,500 | +------+-----------------------------+ 3 rows in set (0.00 sec)
以id分组,把price字段的值打印在一行,逗号分隔,按照price倒序排列
select id,group_concat(price order by price desc) from goods group by id; +------+---------------------------------------+ | id| group_concat(price order by price desc) | +------+---------------------------------------+ |1 | 20,20,10 | |2 | 20| |3 | 500,200| +------+---------------------------------------+ 3 rows in set (0.00 sec)
insert into select from
将查询到的记录插入到某个表中,
INSERT INTO db1_name(field1,field2) SELECT field1,field2 FROM db2_name
要求目标db2必须存在,下面测试一下,有两个表,结构如下
select * from insert_one; +----+--------+-----+-----+ | id | name | age | sex | +----+--------+-----+-----+ | 1 | 田小斯 | 25 | | | 2 | 刘大牛 | 26 | | | 3 | 郑大锤 | 28 | | | 4 | 胡二狗 | 30 | | +----+--------+-----+-----+ 4 rows in set select * from insert_sex; +----+-----+ | id | sex | +----+-----+ | 1 | 1 | | 2 | 2 | | 3 | 1 | | 4 | 2 | +----+-----+ 4 rows in set
从表2中查找性别数据,插入到表1中
into insert_one(sex) select sex from insert_sex; Query OK, 4 rows affected select * from insert_one; +----+--------+-----+-----+ | id | name | age | sex | +----+--------+-----+-----+ | 1 | 田小斯 | 25 | | | 2 | 刘大牛 | 26 | | | 3 | 郑大锤 | 28 | | | 4 | 胡二狗 | 30 | | | 5 | | | 1 | | 6 | | | 2 | | 7 | | | 1 | | 8 | | | 2 | +----+--------+-----+-----+ 8 rows in set
结果很尴尬,我是想要更新这张表的sex字段,而不是插入新的数据,那么这个命令只适用于要把数据导入空表中,所以在上面的实际需要中,我建立了新表mid,利用update来中转并更新数据
代码如下:UPDATE tb1,tb2 SET tb1.address=tb2.address WHERE tb1.name=tb2.name
根据条件匹配,把表1的数据替换为(更新为)表2的数据,表1和表2必须有关联才可以
update insert_one,insert_sex set insert_one.sex = insert_sex.sex where insert_one.id = insert_sex.id; Query OK, 4 rows affected select * from insert_one; +----+--------+-----+-----+ | id | name | age | sex | +----+--------+-----+-----+ | 1 | 田小斯 | 25 | 1 | | 2 | 刘大牛 | 26 | 2 | | 3 | 郑大锤 | 28 | 1 | | 4 | 胡二狗 | 30 | 2 | | 5 | | | 1 | | 6 | | | 2 | | 7 | | | 1 | | 8 | | | 2 | +----+--------+-----+-----+ 8 rows in set
成功将数据更新到insert_one表的sex字段中。
更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL常用函数大汇总》、《MySQL日志操作技巧大全》、《MySQL事务操作技巧汇总》、《MySQL存储过程技巧大全》及《MySQL数据库锁相关技巧汇总》
希望本文所述对大家MySQL数据库计有所帮助。