【问题标题】:mysql select default values from table if user specific ones aren't foundmysql 如果未找到用户特定的值,则从表中选择默认值
【发布时间】:2017-05-18 22:47:18
【问题描述】:

我有一个状态表。

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

等等……

UserID 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

这应该是与“推迟”相同的“状态”,但对于所有用户而言,其措辞与 UserID 4 所具有的不同。

如果有一种更优雅的方式来做到这一点,而不使用 Max,只需选择默认值并添加用户状态,覆盖它们已经存在的默认值?

我需要将它保存在 mysql(即不是 php)中,因为它将成为另一个查询的连接,以便为另一个报告提取用户特定的描述。

【问题讨论】:

    标签: mysql select default


    【解决方案1】:

    我认为这可能是一个解决方案:

    select * from (
        select StatusID,Description from status_description default where default.user_id = 0
        union
        select StatusID,Description from status_description userstatus where ectfsa.user_id = 67
        ) as StatusID;
    

    我不需要结果中的 UserID 或 ID。通过将 * 替换为字段名称来从联合中删除这些,联合会自动删除重复项,或者至少看起来...

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 2015-12-02
      • 1970-01-01
      • 2019-11-24
      • 2019-04-12
      相关资源
      最近更新 更多