MYSQL查询返回更多值

时间:2014-10-20 12:03:57

标签: mysql sql sqlfiddle

问题是我有DATA和SAT表有3个字段,每个字段可能包含值991.下面没有给出正确的列数给出更多数据。如何获得正确的价值。请建议

DATA

id
insurance1
insurance2
insurance3

SAT
id
insurance1
insurance2
insurance3

SELECT * FROM DATA v, SAT s where v.PRIMARY_INSURANCE_ID = '991' 
or v.INSURANCE_ID  = '991' 
or v.INSURANCE_ID = '991' 
and s.INSURANCE_ID = '991' 
or s.INSURANCE_ID = '991' 
or s.INSURANCE_ID = '991';

让我举个例子 例1

DATA    
    id
    insurance1 =991
    insurance2 =56
    insurance3 =22

    SAT
    id
    insurance1=56
    insurance2=23
    insurance3=96

When query is executed. The count should be 1

示例2

DATA    
    id
    insurance1 =991
    insurance2 =56
    insurance3 =22

    SAT
    id
    insurance1=991
    insurance2=23
    insurance3=96

When query is executed. The count should be 2

示例3

DATA    
    id
    insurance1 =991
    insurance2 =56
    insurance3 =991

    SAT
    id
    insurance1=991
    insurance2=23
    insurance3=96

When query is executed. The count should be 3 or 2

2 个答案:

答案 0 :(得分:2)

我建议将其改为join

SELECT *
FROM DATA v JOIN
     SAT
     ON '991' in (v.PRIMARY_INSURANCE_ID, v.INSURANCE_ID) AND 
        '991' in (s.INSURANCE_ID)

您的查询仅提及三个字段。您可以扩展in列表以包含所需的所有列。根据您的表格结构:

SELECT *
FROM DATA v JOIN
     SAT
     ON '991' in (v.INSURANCE1, v.INSURANCE2, v.INSURANCE3) AND 
        '991' in (s.INSURANCE1, s.INSURANCE2, s.INSURANCE3);

编辑:

我认为你根本不想要join

select count(*), count(distinct id)
from (select id, insurance1 as insurance from data union all
      select id, insurance2 from data union all
      select id, insurance3 from data union all
      select id, insurance1 from sat union all
      select id, insurance2 from sat union all
      select id, insurance3 from sat
     ) i
where insurance = '991';

使用count(*)获取3,count(distinct id)获得2.注意:后者假定表之间的id匹配。

答案 1 :(得分:0)

你有两张桌子,你想要计算991。因此表格不一定相关,连接没有意义。只需添加两个计数:

select
  (select count(*) from data where 991 in (insurance1, insurance2, insurance3))
  +
  (select count(*) from sat where 991 in (insurance1, insurance2, insurance3));

BTW:混合AND和OR时要小心: - )