这是我的情况:我有两个表,表A有列:
ID,
Name,
ClassYear,
Classmonth
ID
是主键,没有重复。
表b包含以下列:
ID,
addresstype
addline1
addline2
country,
city,
state,
zip
ID
在table B
中不是唯一的,但这是您链接回table A
的方式。
如果您有多个address
,例如Home
,school
,那么您在table b
中的记录已超过记录。
我的任务是从table A
中选择class year
为>= 2019
的所有人,并选择class year = 2018
为class month
的所有人。 >=5
我没问题。
现在让我感到困惑的是,我有来自table A
的人员列表,我需要查询table b
,而我只想提取同时拥有home
和school
地址类型和地址相同,例如line 1
,line 2
,country
,city
,state
,zip
都是相同的。
我将不胜感激。
答案 0 :(得分:3)
您可以按地址的详细信息分组并计算其具有的不同类型的数量:
SELECT *
FROM table1
WHERE id IN (SELECT id
FROM table2
WHERE addresstype IN ('home', 'school')
GROUP BY id, addline1, addline2, country, city, state, zip
HAVING COUNT(DISTINCT addresstype) = 2)
答案 1 :(得分:1)
SELECT
DISTINCT
student.ID
, student.Name
, student.ClassYear
, student.ClassMonth
FROM
TableA AS student
INNER JOIN TableB AS homeAddress ON
student.ID = homeAddress.ID
AND homeAddress.addressType = 'Home'
INNER JOIN TableB AS schoolAddress ON
student.ID = schoolAddress.ID
AND schoolAddress.addressType = 'School'
AND homeAddress.line1 = schoolAddress.line1
AND homeAddress.line2 = schoolAddress.line2
AND homeAddress.country = schoolAddress.country
AND homeAddress.city = schoolAddress.city
AND homeAddress.state = schoolAddress.state
AND homeAddress.zip = schoolAddress.zip
WHERE
student.classYear >= 2019
OR (student.ClassYear = 2018 AND student.classMonth >= 5)
;