需要一个mysql查询通过分组和条件获取结果

时间:2018-03-08 10:36:04

标签: mysql

我需要通过分组fid以及fid的状态字段需要为1来获取所有列

id fid status
1   1    1
2   1    0
3   2    1
4   2    1
5   3    0
6   4    1

在上表中我需要通过分组fid来获取fid,并且所有分组行的状态必须为1 这里的结果将是2,4

3 个答案:

答案 0 :(得分:1)

试试这个 -

SELECT fid, status FROM `table_name` WHERE status=1 GROUP BY fid;

答案 1 :(得分:1)

试试这个:

    private void StatusChecker()
            {
                switch (Issue.Status)
                {
                    case IssueStatus.Unresolved:
                        StatusUnresolvedOpacity = 1;
                        StatusInProgressOpacity = 0.5;
                        StatusDoneOpacity = 0.5;
                        StatusText = "Unresolved";
                        break;
                    case IssueStatus.InProgress:
                        StatusUnresolvedOpacity = 0.5;
                        StatusInProgressOpacity = 1;
                        StatusDoneOpacity = 0.5;
                        StatusText = "In Progress";
                        break;
                    case IssueStatus.Done:
                        StatusUnresolvedOpacity = 0.5;
                        StatusInProgressOpacity = 0.5;
                        statusDoneOpacity = 1;
                        StatusText = "Done";
                        break;
                }
            }

请参阅MySQL GROUP_CONCAT Function了解相关信息。

答案 2 :(得分:1)

尝试此查询:

SELECT 
    reqd_stat.fid1
FROM
    (SELECT 
        *
    FROM
        (SELECT 
        fid fid1, COUNT(*) stat
    FROM
        stk_grp
    GROUP BY fid1) all_stats
    JOIN (SELECT 
        fid fid2, COUNT(*) stat1
    FROM
        stk_grp
    WHERE
        status = 1
    GROUP BY fid2) pos_stats ON pos_stats.fid2 = all_stats.fid1
    HAVING pos_stats.stat1 = all_stats.stat) reqd_stat;

阐释:

  1. all_stats表格将fid无条件地分组
  2. pos_stats表将fidstatus=1条件
  3. 分组
  4. having用于比较状态列的计数(如果它们相等,那么属于该组的所有fid都有status=1
  5. 只需打印fid即可获得所需的输出