以下是我的表,即学生ID是两个表中的公共字段。我希望在单个查询中获取两个表数据。还可以获取学生的最新数据。
table A:
student_id name surname email
------------------------------------------------
1 ABC LLL abc@gmail.com
2 PQR SSS pqr@gmail.com
Table B:
student_id Assignment_Id Assignment_Name last_submited
---------------------------------------------------------------------
2 1 asign_1 sub_0001
1 2 asign_2 sub_0002
2 3 asign_2 sub_0003
我想要确切的输出,如: -
student_id Assignment_Id email last_submited
--------------------------------------------------------------
2 3 pqr@gmail.com sub_0003
我使用了以下查询来获取最近的记录但却混淆了如何获取电子邮件ID。
SELECT assignment_id,
student_id,
last_submited
FROM tableB
WHERE student_id= '2'
ORDER BY assignment_id DESC LIMIT 1
答案 0 :(得分:2)
您可以使用JOIN
select tableB.assignment_id,
tableB.student_id,
tableB.last_submited,
tableA.email
from tableB INNER JOIN
tableA ON tableB.student_id = tableA.student_id
where tableB.student_id= '2'
order by tableB.assignment_id desc
limit 1
INNER JOINs
用于返回数据在两个表中的数据(因此en表将存在于tableA和tableB中)。
LEFT JOINs
。
所以,假设你有
TABLEA
-------
1
2
和
TABLEB
-------
1
SELECT *
FROM TABLEA INNER JOIN
TABLEB ON TABLEA.ID = TABLEB.ID
将返回
1,1
尽管
SELECT *
FROM TABLEA LEFT JOIN
TABLEB ON TABLEA.ID = TABLEB.ID
将返回
1,1
2,NULL
答案 1 :(得分:1)
加入两个表格,
SELECT B.assignment_id,
B.student_id,
A.email_id ,
B.last_submited
FROM tableB 'B',
tableA 'A'
WHERE B.student_id= '2'
AND A.student_id=B.student_id
ORDER BY assignment_id DESC LIMIT 1
答案 2 :(得分:1)
您需要使用join
SELECT a.student_id,
b.Assignment_id,
a.email,
b.last_submitted
FROM a
INNER JOIN b ON a.student_id = b.student_id
WHERE a.student_id= '2'
ORDER BY b.assignment_id DESC LIMIT 1