0
我有一個狀態表。如果沒有找到用戶特定的表,mysql會從表中選擇默認值
ID UserID StatusID Description
1 0 0 ready
2 0 1 on hold
3 0 2 cancelled
4 3 1 waiting
5 3 2 deleted
6 3 4 waiting on supplier
7 4 5 postponed
等等
用戶名0時我的默認描述。如果沒有具有相同狀態ID的用戶值,我想爲用戶提取所有狀態文本和默認值。 例如用戶ID 3應該返回
ID UserID StatusID Description
1 0 0 ready
4 3 1 waiting
5 3 2 deleted
6 3 4 waiting on supplier
例如用戶ID 4應返回
ID UserID StatusID Description
1 0 0 ready
2 0 1 on hold
3 0 2 cancelled
7 4 5 postponed
用戶ID 7應該返回
ID UserID StatusID Description
1 0 0 ready
2 0 1 on hold
3 0 2 cancelled
到目前爲止我有這:
select description.* from status_description description
join (
select max(id) as maxid from (
select * from status_description default where default.user_id = 0
union
select * from status_description userstatus where ectfsa.user_id = 67
) as subset
group by subset.ID
) as newest_desc on newest_desc.maxid = description.id
order by StatusID asc;
我在哪裏工會用戶狀態和默認狀態,然後將每個statusID的最大ID加回到原始表中以獲取用戶和默認值。
這可以正常工作,直到有人用更高的ID添加新的USERID0狀態。例如,我們決定所有用戶現在應該對「推遲」選項,我們添加一行
ID UserID StatusID Description
8 0 5 next week
這應該是相同的「狀態」爲「推遲」,但措辭不同爲所有用戶4有什麼用戶名。
如果在不使用Max的情況下采用更優雅的方式,只需選擇默認值並添加用戶狀態覆蓋已存在的默認值?
我需要保持在MySQL內(即不是PHP),因爲它將成爲另一個查詢的連接,以提取另一個報表的用戶特定描述。