MySQL从2个不同的表中的一行中选择多行

时间:2014-02-11 13:06:13

标签: mysql sql

我遇到这种情况:

Table A (Ex. Dog's name):
ID | Name
1  | Nabu
2  | Lapo
3  | Kim
3  | Bau

Table B (Ex. Dog's characteristics):
ID | AID | BID | BV
1  |  1  |  1  |  1
2  |  1  |  2  |  1
3  |  1  |  3  |  0
4  |  2  |  1  |  1
5  |  2  |  2  |  0
6  |  2  |  3  |  1
7  |  3  |  1  |  0
8  |  3  |  2  |  1
9  |  3  |  3  |  1
10 |  4  |  1  |  1
11 |  4  |  2  |  1
12 |  4  |  3  |  1

我需要使用B特征字段在A中进行“精确搜索”

实施例

(BID = 1 && BV = 1) AND (BID = 2 && BV = 1)  have to return A.ID = 1 & 4
(BID = 1 && BV = 0) AND (BID = 2 && BV = 1)  have to return A.ID = 3

如何在1个或更少的查询中执行此操作,每个特征和比较!?

谢谢!

2 个答案:

答案 0 :(得分:2)

如果您自己加入桌子:

SELECT A.id FROM A 
LEFT JOIN B as B1 on A.ID = B1.AID
LEFT JOIN B as B2 on A.ID = B2.AID and B1.ID != B2.ID
WHERE
(B1.BID = 1 && B1.BV = 1) AND (B2.BID = 2 && B2.BV = 1)

您应该能够找到A中的所有行,其中B的两个匹配条目的B.IDs不同。

答案 1 :(得分:1)

您可以使用聚合和having子句执行此操作:

select AID
from table B
group by AID
having sum(BID = 1 AND BV = 1) > 0 and
       sum(BID = 2 AND BV = 1) > 0;

having子句中的每个条件都会计算满足其中一个条件的行数。您的逻辑要求两者都存在,因此行数必须大于0。