我有一张注册表:
+--------------+-------------+----------------+
| enrolleeId | int(11) | auto_increment |
| officeId | int(11) | |
| fName | varchar(45) | |
| mName | varchar(45) | |
| lName | varchar(45) | |
| dateOfBirth | date | |
| placeOfBirth | int(11) | |
| race | int(11) | |
| role | varchar(45) | |
+--------------+-------------+----------------+
我有一张徽章的表:
+----------------+----------+----------------+
| badgeId | int(11) | auto_increment |
| enrolleeId | int(11) | |
| expirationDate | datetime | |
| badgeImage | blob | |
+----------------+----------+----------------+
我有一个状态表:
+-----------+-------------+
| stateId | int(11) |
| code | varchar(10) |
| stateName | varchar(45) |
+-----------+-------------+
我有一张种族的表:
+----------+-------------+
| raceId | int(11) |
| code | varchar(10) |
| raceName | varchar(45) |
+----------+-------------+
我要查询注册情况,这是所使用的:
SELECT * FROM enrollment e
INNER JOIN state pob on e.placeOfBirth = pob.stateId
INNER JOIN race r on e.race = r.raceId
WHERE e.enrolleeId = 123;
这就是我得到的:
'enrolleeId', 'officeId', 'fName', 'mName', 'lName', 'dateOfBirth', 'placeOfBirth', 'race', 'role', 'stateId', 'code', 'stateName', 'raceId', 'code', 'raceName'
'123', '1', 'Joe', 'A', 'Smith', '1970-01-01', '49', '2', 'Software Developer', '49', '49', 'Virginia', '2', '2','Caucasian'
绝对正确。
现在我要做的是在徽章表中添加一个名称,以便对雇员的每个查询都将显示其徽章编号,因此我添加了另一个联接:
SELECT * FROM enrollment e
INNER JOIN state pob on e.placeOfBirth = pob.stateId
INNER JOIN race r on e.race = r.raceId
INNER JOIN badge b on e.enrolleeId = b.enrolleeId
WHERE e.enrolleeId = 123;
运行此查询时,这是我得到的:
'enrolleeId', 'officeId', 'fName', 'mName', 'lName', 'dateOfBirth', 'placeOfBirth', 'race', 'role', 'badgeId', 'enrolleeId', 'expirationDate', 'badgeImage'
'123', '1', 'Joe', 'A', 'Smith', '1970-01-01', '49', '2', 'Software Developer', '456', '123', '2019-01-01 13:00:00', '[blob]'
'123', '1', 'Joe', 'A', 'Smith', '1970-01-01', '49', '2', 'Software Developer', '457', '123', '2019-01-01 13:00:00', '[blob]'
'123', '1', 'Joe', 'A', 'Smith', '1970-01-01', '49', '2', 'Software Developer', '458', '123', '2019-01-01 13:00:00', '[blob]'
'123', '1', 'Joe', 'A', 'Smith', '1970-01-01', '49', '2', 'Software Developer', '459', '123', '2019-01-01 13:00:00', '[blob]'
'123', '1', 'Joe', 'A', 'Smith', '1970-01-01', '49', '2', 'Software Developer', '460', '123', '2019-01-01 13:00:00', '[blob]'
'123', '1', 'Joe', 'A', 'Smith', '1970-01-01', '49', '2', 'Software Developer', '461', '123', '2019-01-01 13:00:00', '[blob]'
.
.
.
这是正确的。我获得了徽章信息,但获得了每个员工的所有徽章ID,但是我没有获得所有的州和种族信息。
我如何只让一名雇员获得其徽章信息?
谢谢!
答案 0 :(得分:0)
更改此行
INNER JOIN badge b on e.enrolleeId = b.enrolleeId
对此:
INNER JOIN (SELECT *,
ROW_NUMBER() OVER (PARTITION BY enrolleeId ORDER BY anyColumnName) rn
FROM badge) b
ON e.enrolleeId = b.enrolleeId and b.rn = 1