简体   繁体   English

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

[英]MySQL Select multiple rows from one row in 2 different tables

I have this situation: 我有这种情况:

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

I need to make an "exact search" in A using the B characteristics fields 我需要使用B特征字段在A中进行“精确搜索”

Ex. 例如

(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

How can i do this in 1 or less then one query each characteristic and a comparaction!? 我该如何在1个或更少的时间内执行此操作,然后对每个特征和一个比较项进行一次查询!

Thanks! 谢谢!

If you join the table on itself: 如果您自己加入表格:

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)

You should be able to find all rows in A where you two matching entries from B where the B.IDs are different. 您应该能够在A中找到所有行,而B中的两个匹配条目的B.ID不同。

You can do this with aggregation and a having clause: 您可以使用聚合和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;

Each condition in the having clause counts the number of rows that meet one of the conditions. 中每个条件having子句计数满足的条件之一的行数。 Your logic requires that both be present, so the number of rows needs to be bigger than 0. 您的逻辑要求两者都存在,因此行数必须大于0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM