MySQL查询用于限制目的

时间:2014-04-23 07:09:31

标签: mysql

我有4张桌子:

  1. 人员
  2. yes_vote - >那些投票赞成是'
  3. 的官员
  4. no_vote - >那些投票的人员没有'
  5. not_voted - >尚未投票的官员
  6. 我做了什么:

    1. 检查该人员是否存在于yes_vote。
    2. 现有数据不会显示为yes_vote的选项。

      SELECT * 
      FROM officers 
      WHERE uuid NOT IN (SELECT officer_uuid 
                        FROM ".$table_vote." v 
                        WHERE v.resolution_uuid = '".$resolution_uuid."')"
      
    3. 我必须做的事情:

      1. 检查该人员是否在三票表中。
      2. 如果官员已经包含在yes_vote中,则他/她不得在no_vote和not_voted中显示为选项,等等。

2 个答案:

答案 0 :(得分:0)

恕我直言,你的桌子结构错了但是......

如果要检查3个表中的并行存在:

SELECT * FROM officers o
WHERE EXISTS
    (SELECT 'YES' FROM yes_vote y WHERE y.officer_uuid = o.id AND y.resolution_id = 'YOUR_VAR')
AND EXISTS
    (SELECT 'NO' FROM no_vote n WHERE n.officer_uuid = o.id AND y.resolution_id = 'YOUR_VAR')
AND EXISTS
    (SELECT 'NOTVOTED' FROM not_voted nv WHERE nv.officer_uuid = o.id AND y.resolution_id = 'YOUR_VAR')

我建议你改变你的表结构,而不是3个不同的表,你可以用官员的投票创建一个表如下:

TABLE VOTE:

id (PK of vote table)
officer_uuid (FK to officers table)
resolution_uuid (FK to resolutions table)
vote_kind (with check Y, N, X)

答案 1 :(得分:0)

1)检查该人员是否在三张选票表中

SELECT * FROM officers WHERE uuid IN (SELECT officer_uuid FROM yes_vote union SELECT officer_uuid FROM no_vote  union SELECT officer_uuid FROM not_voted )   

2)如果官员已经包含在yes_vote中,则他/她不得在no_vote和not_voted中显示为选项,等等。

我认为你想要列出在多个表中有条目并且不应该发生的官员。 假设您要查找在yes_vote和no_vote

中有多个条目的人员
select * from officers where uuid in (   SELECT officer_uuid  FROM yes_vote inner join no_vote on yes_vot.officer_uuid =no_vote.officer_uuid )

同样适用于not_voted

如果你想找到其他官员已经给出了他/她的投票,你可以使用以下查询

select if(b.uuid is null,'still not voted','already voted'),a.officer_name from officers  a left join  (SELECT officer_uuid as uuid FROM yes_vote union SELECT officer_uuid as uuid FROM no_vote  union SELECT officer_uuid as uuid FROM not_voted )b   on a.uuid =b.uuid