您的位置:首页 > 数据库 > MySQL

Mysql学习过程中的一点记录(行列调换)

2018-01-30 01:02 483 查看
两个表 

user.id   user.name   user.age 

phones.id   phones.phone_num   phones.user_id

1. 简单的左查询

select phones.user_id,users.name,users.age from users Left JOIN phones on phones.user_id = users.id

因为左查询遍历users表,而user表中有些用户并未登记号码,所以可能会出现空值情况,改善一下

select phones.user_id,users.name,users.age from users Left JOIN phones on phones.user_id = users.id where user_id is not Null 

或者改成右查询,即可

2.上面的语句如果要简写 phones.user_id 为 b.user_id 的时候,请全部都改成a b的形式

3.至于inner join和cross join

cross join是笛卡尔积,理论上不应该支持on语法

如果非要解释……那应该就是cross join先生成笛卡尔积然后过滤on,而inner join是直接基于on给的条件进行过滤

4.简单的求和查询

user.id+name

user_score.id+score

select a.name,sum(b.score) from user a join user_score b on a.id = b.id GROUP BY a.name

找出每个user.id分数的总和

name      sum(b.score)

izaya 8

mcc  11

timer 23

5.讲上列数据行和列调换显示,大概为:

izaya timer mcc 

 8  23 11

灵活使用join语句可以把列合并的原理(ps:默认join是内连)

select * from (

select sum(b.score) as 'newTimer' from user a join user_score b on a.id = b.id and name='timer' ) a 

join 

(select sum(b.score) as 'newMCc' from user a join user_score b on a.id = b.id and name='mcc')  b 

join 

(select sum(b.score) as 'newIzaya' from user a join user_score b on a.id = b.id and name='izaya') c 

from 后应该是表名,可是现在是查询结果,所以用简写代替表明,此处简写abc是必需的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql