0
我需要的結果是這樣的:mysql的分組,連接和ORDER BY問題
person_id last_name first_name region_id region name
1 barnum phineas 1 maricopa
2 loman willy 2 pima
2 loman willy 3 pinal
2 loman willy 4 santa cruz
3 kay mary 5 cochise
3 kay mary 6 gila
3 kay mary 7 graham
我的代碼是這樣的:
select `person_id`, `last_name`, `first_name`,
`Region_id`, `name` AS 'Region Name'
from `sales_region`
inner join sales_people
on `person_id` = `person_id`
group by `region_id` asc, `person_id`
having `person_id`in ('1','2','3')
order by `person_id`,`region_id` asc
;
它給了我這樣的:
person_id last_name first_name Region_id "Region Name"
1 barnum phineas 1 maricopa
1 barnum phineas 2 pima
1 barnum phineas 3 pinal
1 barnum phineas 4 santa cruz
1 barnum phineas 5 cochise
1 barnum phineas 6 gila
1 barnum phineas 7 graham
2 loman willy 1 maricopa
2 loman willy 2 pima
2 loman willy 3 pinal
2 loman willy 4 santa cruz
2 loman willy 5 cochise
2 loman willy 6 gila
2 loman willy 7 graham
3 kay mary 1 maricopa
3 kay mary 2 pima
3 kay mary 3 pinal
3 kay mary 4 santa cruz
3 kay mary 5 cochise
3 kay mary 6 gila
3 kay mary 7 graham
我不知道如何使它如上所示顯示。我曾嘗試搞亂順序和分組,我得到了同樣的結果。我不確定如何將結果縮小到結果應該如何。
感謝您的快速響應!兩次嘗試都會出錯。沒有重疊的列信息。 person_id只存在於sales_people中。 region_id只存在於sales_region中。我只是加入表格,所以我可以從多列中進行選擇。當我嘗試寫兩個選擇查詢時,我收到錯誤。 – talesin22
你沒有一個包含'region_id'和'person_id'列的數據透視表嗎?名字像'sales_people_region'或'people_region'或類似的? –
我確實有一個名爲sales_people_region的表,它具有person_id和region_id。我沒有把它包含在查詢中,因爲它似乎沒有必要。 – talesin22