简体   繁体   中英

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

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!?

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.

You can do this with aggregation and a having clause:

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. Your logic requires that both be present, so the number of rows needs to be bigger than 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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