SQL查询更正一对多表

时间:2017-09-14 07:08:01

标签: mysql

我有两个表,一个是用户,第二个是user_education.One用户可以有多个教育列表,所以我想获得最新的用户教育列表

users
===============
1-id
2-email

member_experience 
==============
1-id
2-user_id
3-designation

用户ID 1在user_education中有4个进入,所以我想让最后一条记录输入用户名称

原始完整查询就像这样

SELECT u.id,u.name,u.gender,u.email,file_managed.file_name,file_managed.file_path 
from users as u 

INNER JOIN member_experience on (SELECT uid  FROM member_experience where member_experience.uid=u.id ORDER BY id DESC LIMIT 1)=u.id 

LEFT JOIN file_managed on file_managed.id= u.fid 

where u.user_type ='individual' AND u.gender='male'


"INNER JOIN member_experience on (SELECT uid  FROM member_experience where member_experience.uid=u.id ORDER BY id DESC LIMIT 1)=u.id "

这个部分有问题,因为用户在member_experience表中有很多记录,但我想只获得一个最新记录。

感谢

1 个答案:

答案 0 :(得分:0)

将最后一条记录的获取权交给where语句。

drop table if exists member_experience;     create table member_experience(id int auto_increment primary key,userid int);

import matplotlib.pyplot as plt
import datetime as dt
#data1
x=['200101','200102','200103','200104','200105','200106','200107','200108',
   '200109','200110','200111','200112','200201','200202','200203','200204',
   '200205','200206','200207','200208','200209']
x = [dt.datetime.strptime(i, '%Y%m') for i in x] 
y=[30.2,37.6,34.7,27.1,31.9,43.9,42.4,42.3,34.4,40.0,47.2,
   40.8,34.7,27.1,31.9,43.9,42.4,42.3,34.4,40.0,47.2]

#data2   
q=['200106','200107','200108','200206','200207','200208']
q = [dt.datetime.strptime(i, '%Y%m') for i in q] 
w=[19.7,18.6,15.2,17.3,16.9,18.2]

for i, xi in enumerate(x):
    if xi not in q:
        w.insert(i, None)


plt.plot(x,y, '-r')    
plt.plot(x,w,':b')


plt.show()

或者如果你想包括那些没有经验的人

insert into member_experience (userid) values
(1),(2),(1);

select * from member_experience

SELECT u.id,m.id 
from users as u 
join member_experience m on m.userid = u.id
where m.id = (SELECT max(m.id)  FROM member_experience m where m.userid = u.id)
order by u.id