当元素计数超过1

时间:2015-11-30 22:57:24

标签: mysql inner-join

我需要做内连接的反面。

我有例如“TypeComponent”表。我添加了MaxAllowed列

IDTypeElement    Type           MaxAllowed
   Type1         battery            1
   Type2         temperature        1
   Type3         pressure           3

我有表发射器,我只能有1个电池,1个温度和3个压力元件

ID    IDTransmitter   IDTypeElement   
1         A              Type1
2         A              Type2
3         A              Type3
4         A              Type3
5         A              Type3

6         B              Type1
7         B              Type3

当我们向发射器添加组件时,我需要能够删除我们已经拥有的TypeElement。例如,发射器“B”,我希望能够在我的列表框中只获得允许的组件。在这里,我的意思是,列表框必须只包含“Type2”(温度)和“Type3”(压力),因为我们只允许一个“Type1”(电池),我们已经有一个。另一方面,我们可以有3个“Type3”(压力),我们只有一个。

所以,我尝试使用该查询

SELECT IDTypeElement from typeelement
WHERE IDTypeElement not in (SELECT IDTypeElement FROM transmitter WHERE IDTransmitter="B")

我的问题是,我希望能够获取“Type3”,因为我们允许有3次“Type3”,但是使用该查询,我只得到“Type2”...有没有办法告诉极限一个元素?有人可以帮帮我吗?

希望你理解我的问题(和我的英语)。

如果我以IDTranmistter:B为例,使用类似上面的查询,我想在我的列表框中输入:“Type2”和“Type3”

2 个答案:

答案 0 :(得分:2)

下面的内容应该有效:

Select e.IDTypeElement
from TypeComponent e LEFT JOIN
(
select IDTransmitter, IDTypeElement, count(*) as used
from Transmitter 
group by IDTransmitter,IDTypeElement
) t
on e.IDTypeElement = t.IDTypeElement
and t.IDTransmitter = 'B'
where (e.MaxAllowed-ifnull(t.used,0))>0

请检查sqlfiddle @ http://sqlfiddle.com/#!9/c8743/5

答案 1 :(得分:0)

你可以做左连接

<强>表格

mysql> select * from typecomponent
    -> ;
+---------------+-------------+------------+
| idtypeelement | type        | maxallowed |
+---------------+-------------+------------+
| Type1         | battery     |          1 |
| Type2         | temperature |          1 |
| Type3         | pressure    |          3 |
+---------------+-------------+------------+
3 rows in set (0.00 sec)

mysql> select * from transmitter;
+----+---------------+---------------+
| id | idtransmitter | idtypeelement |
+----+---------------+---------------+
|  1 | A             | Type1         |
|  2 | A             | Type2         |
|  3 | A             | Type3         |
|  4 | A             | Type3         |
|  5 | A             | Type3         |
|  6 | B             | Type1         |
|  7 | B             | Type3         |
+----+---------------+---------------+
7 rows in set (0.00 sec)

<强>查询:

select idtypeelement from (select tc.idtypeelement, tc.maxallowed, count(t.idtypeelement) as usedComponents from typecomponent tc left join transmitter t on t.idtypeelement = tc.idtypeelement and t.idtransmitter='B' group by 1,2 having usedComponents < tc.maxallowed) t;
+---------------+
| idtypeelement |
+---------------+
| Type2         |
| Type3         |
+---------------+
2 rows in set (0.00 sec)
相关问题