我有3個具有多對多關係的表。我想爲特定用戶和特定產品選擇該產品的最後插入行。MySQL選擇具有特定條件的行,最後一行插入的條件爲多對多
表 '用戶' 包含用戶的個人信息:
userID persID firstName lastName gender
42 9559000 Jane Rae female
43 9559001 John Doe male
.
.
.
表 '存放1' 包含產品信息:
storageID product productAttribute productSize storageQTY
1 shirt red S 10
2 shirt blue M 10
.
.
.
13 shirt green L 10
14 shirt green XL 9
15 shirt green XXL 7
.
.
39 trousers male 60 10
40 trousers male 62 8
.
.
59 shoes standard 41 10
60 shoes standard 42 7
61 shoes standard 43 10
62 shoes standard 44 10
63 shoes standard 45 9
.
.
72 jacket red L 10
73 jacket red XL 9
74 jacket red XXL 6
和表activityRecords:
recordsID userID storageID startDate expDate
99 43 15 2017-09-14
100 43 74 2017-09-14
101 43 39 2017-09-14
102 43 13 2017-09-14
103 43 14 2017-09-14
104 43 40 2017-09-14
105 43 14 2017-09-14
106 43 63 2017-09-14
107 43 59 2017-09-14
到目前爲止,我只有產生與特定用戶有關的產品的最大值的代碼。
select
persID,
firstName,
lastName,
gender,
max(case when storage1.product = 'shoes' then storage1.productSize end) shoes,
max(case when storage1.product = 'trousers' then storage1.productSize end) trousers,
max(case when storage1.product = 'shirt' then storage1.productSize end) shirt,
max(case when storage1.product = 'shirt' then storage1.productAttribute end) color,
max(case when storage1.product = 'jacket' then storage1.productSize end) jacket,
startDate,
expDate
from activityRecords
left join user on activityRecords.userID = user.userID
left join storage1 on activityRecords.storageID = storage1.storageID
where persID='9559001'
group by persID, firstName, lastName, gender, startDate, expDate
order by persID
這導致這樣的:
persID firstName lastName gender shoes trousers shirt color jacket startDate expDate
9559001 John Doe male 45 null null null null 2017-09-14
9559001 John Doe male null 62 null null null 2017-09-14
9559001 John Doe male null null XXL green null 2017-09-14
9559001 John Doe male null null null null XXL 2017-09-14
,但我想這一點:
persID firstName lastName gender shoes trousers shirt color jacket startDate expDate
9559001 John Doe male 41 null null null null 2017-09-14
9559001 John Doe male null 62 null null null 2017-09-14
9559001 John Doe male null null XL green null 2017-09-14
9559001 John Doe male null null null null XXL 2017-09-14
因爲鞋號41是鞋activityRecords表的最新條目(recordsID 107) shirt size XL是activityRecords表中襯衫的最新條目(recordsID 105)。 雖然現在有鞋子選擇記錄ID 106和襯衫選擇記錄ID 99.我知道這是相關的,因爲我的選擇代碼(使用max(case when ...)),但我不知道如何選擇特定產品和人員的最新條目。任何人都可以幫助我呢?謝謝
這表明持續超過一排扁平化的結構,但它的確定我。謝謝 – tomas