如何从另一个表填充单元格值?

时间:2019-07-09 18:36:39

标签: mysql

我有两个桌子。 A和B

public class FetchReputationUseCaseSync {

    private GetReputationHttpEndpointSync mGetReputationHttpEndpointSync;

    public FetchReputationUseCaseSync(GetReputationHttpEndpointSync getReputationHttpEndpointSync) {
        this.mGetReputationHttpEndpointSync = getReputationHttpEndpointSync;
    }

    public UseCaseResult fetchReputation() {
        GetReputationHttpEndpointSync.EndpointResult result;

        try{
            result = mGetReputationHttpEndpointSync.getReputationSync();

        }catch (NetworkErrorException e) {
            e.printStackTrace();
            return UseCaseResult.FAILURE;
        }

        switch(result.getStatus()) {
            case SUCCESS:
                return UseCaseResult.SUCCESS;

            case GENERAL_ERROR:
                return UseCaseResult.FAILURE;
            default:
                throw new RuntimeException("invalid status: " + result);
        }
    }

    public enum UseCaseResult{
        SUCCESS, FAILURE
    }
}

结果如下:

enter image description here

SELECT projectid, statusid from A; 

结果如下:

enter image description here

现在如何获得如下结果,将所有stutusid替换为表B中的值。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用JOIN

SELECT A.projectid, B.status from A JOIN b ON A.statusid = b.statusid;

编辑:

  

我想将所有其他状态代码都替换为另一个表B中的“其含义”。因此,“ join”将不会执行此工作,而只会显示A和B表中匹配的结果

我不理解要求。这正是联接正在执行的操作,显示了第二个表中的相应值。例如,如果您没有特定的代码,则应使用LEFT OUTER JOIN

SELECT A.projectid, COALESCE(B.status, 'Unknown') AS status
from A 
LEFT JOIN b ON A.statusid = b.statusid;

如果表B上没有重复项,也许您正在搜索相关子查询(但它实际上与JOIN相同)

SELECT A.projectid,
       (SELECT B.status FROM B WHERE A.statusid = b.statusid) AS status
FROM A 

-- if it returns error query returned more than one row then b.statusid is not unique
    SELECT A.projectid,
       (SELECT B.status FROM B WHERE A.statusid = b.statusid ORDER BY ... LIMIT 1) AS status
FROM A