通过比较从mysql中获取数据

时间:2018-04-24 08:35:32

标签: mysql sql

我有下面提到的表:

id      string    var
1       asdadf    ab
1       asdadf    ac
2       axdrtg    ar
2       axadtg    at

我想获取那些记录,其中同一id我们有相同stringvar不同。

输出

id      string    var
1       asdadf    ab
1       asdadf    ac

我尝试过:select id,string,var from table where string>1 group by id;

4 个答案:

答案 0 :(得分:0)

SELECT `id`, `string`, `var`
FROM TABLE1
WHERE `id` IN
(
SELECT `id`
FROM TABLE1
GROUP BY `id`, `string`
HAVING COUNT(*) > 1
)

<强>输出

id  string  var
1   asdadf  ab
1   asdadf  ac

<强>演示

  

http://sqlfiddle.com/#!9/a09681/2

答案 1 :(得分:0)

您可以使用exists

select * 
from table t
where exists (select 1 from Table 
              where id = t.id 
              group by string 
              having count(*) > 1) and
      exists (select 1 from table
              where id = t.id 
              group by var 
              having count(*) = 1);

答案 2 :(得分:0)

希望这会有所帮助:

    select id,string,var from table where id in (select id from table group by string having count(id)>1)

答案 3 :(得分:0)

试试这个: -

select id count(*) as i,string count(*) as c from table
      group by string having c > 1 && i > 1
                     order by c desc