Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mysql中获取同一列中多个字段的查询_Mysql - Fatal编程技术网

在mysql中获取同一列中多个字段的查询

在mysql中获取同一列中多个字段的查询,mysql,Mysql,我正在使用mysql数据库 id | comment --------+--------------- 1121 | Accounting 1121 | Shipping 1121 | Receiving 1121 | Testing 1122 | Accounting 1122 | Receiving 我想写这样一个查询,这样o/p将是这样的-: id | comment

我正在使用mysql数据库

     id | comment       
--------+--------------- 
   1121 |    Accounting
   1121 |    Shipping  
   1121 |    Receiving
   1121 |    Testing
   1122 |    Accounting
   1122 |    Receiving
我想写这样一个查询,这样o/p将是这样的-:

     id | comment       
--------+--------------- 
   1121 |    Accounting
   1121 |    Shipping  
   1121 |    Receiving
   1121 |    Testing
所以我想要会计、发货、接收和测试评论

select T1.id from mytable T1, mytable T2, mytable T3, mytable T3 where T2.id=T1.id and T3.id=T1.id and T4.id=T1.id and T1.comment='Accounting' and T2.comment='Shipping' and T3.comment='Receiving' and T4.id='Shipping'

有人能给我指点迷津吗???

你想选择所有的ID,它们都有4条注释吗?在您的示例中,1121有4个不同的注释(就像一个“状态”,对吗?),而1122只有2个状态(注释)

  • 如果您只需要包含所有四条注释的记录的
    id
    ,则可以按
    id
    分组,并为包含所需数量记录的组筛选这些组:

    SELECT   id
    FROM     my_table
    WHERE    comment IN ('Accounting', 'Shipping', 'Receiving', 'Testing')
    GROUP BY id
    HAVING   COUNT(*) = 4
    
    在电视上看

  • 如果需要此类
    (id,comment)
    对的完整记录,可以将结果与原始表合并:

    SELECT * FROM my_table NATURAL JOIN (
      SELECT   id
      FROM     my_table
      WHERE    comment IN ('Accounting', 'Shipping', 'Receiving', 'Testing')
      GROUP BY id
      HAVING   COUNT(*) = 4
    ) t
    WHERE comment IN ('Accounting', 'Shipping', 'Receiving', 'Testing')
    
    在电视上看


请注意,如果您的数据模型不能保证
(id,comment)
对的唯一性,则需要将
计数(*)
替换为(性能较差的)
计数(不同的注释)
在上述查询中。

对于多次出现的注释,您希望使用哪个
id
呢?对于id 1121,我需要注释。根据这些注释,我必须更新另一个注释table@Iswariya苏塔卡尔:你为什么决定让“会计”选择1121而不是1122?是否可以选择1122而不是1121?什么是条件?如果特定id的进程包含我说过的所有注释,那么我需要关闭该进程,然后为什么不使用
WHERE
子句简单地指定一个筛选条件:例如
SELECT*FROM my_table,其中id=1121
?“否。我想要该特定id”-然后它很简单:从mytable中选择*,其中id=1121如果我有时对该id使用此选项,则它只有会计和发货或会计,发货方式是这样的,但我需要所有四条注释。如果四条注释都在那里,我需要在另一个表中将状态更新为closed,那么上面的SQL解决了这个问题。它只查找包含所有4条注释的ID。只需将“mytable”替换为您的表名:从mytable T1、mytable T2、mytable T3、mytable T3中选择T1.id,其中T2.id=T1.id和T4.id=T1.id和T1.comment='Accounting'以及T2.comment='Shipping'和T3.comment='Receiving'和T4.id='Shipping'