简体   繁体   中英

Find records from a table that, among associated records in another table, don't have a record with a specific field value

is there a way to find in one query all the records from a table that among associated records in another table don't have a record with a specific field value?

To better explain here is the example:

A record in Table A has many records in Table B, each record in Table B belongs to one record in Table A (N:1)

Table A:
record 1(id: 1, name: happy)
record 2(id: 2, name: sad)

Table B:
record 1(id:1, name: dog, table_a_id: 1)
record 2(id:2, name: cat, table_a_id: 1)
record 3(id:3, name: mouse, table_a_id: 1)
record 4(id:4, name: dog, table_a_id: 2)
record 6(id:6, name: mouse, table_a_id: 2)

I would like to obtain the records in Table A that don't have, among the associated records of table B, the one with name: cat, in the little example above "Table A.record 2", since among associated records of "Table A.record 1" there's "Table B.record 2" which name's field is equal to cat.

Thanks for the help, Gabriele

I was trying to understand this but had a little trouble, here are 2 queries:

This query will return a join of a and b tables excluding records with the name "cat":

SELECT *
FROM table_a AS a
JOIN table_b AS b
ON a.id = b.table_a_id
WHERE b.name != "cat"

And this query will return only records with the name "cat":

SELECT *
FROM table_a AS a
JOIN table_b AS b
ON a.id = b.table_a_id
WHERE b.name = "cat"

I hope this is what you were looking for. One thing to keep in mind, if you're going to be filtering on these columns, make sure that you have your tables properly indexed. You might not see any lag on small data, but as it grows the queries will slow down with this type of look up.

You could use a left join and check for null values in the joined table:

SELECT A.* FROM A
LEFT JOIN B ON A.id = B.table_a_id AND B.name = 'cat'
WHERE B.id IS NULL

This will select all records in A with the cats in B, but when a cat that matches the record in A is not found it will select null for all fields of B (that's what the left join does). The where clause then selects only those records where a matching B isn't found, leaving only the records from A for which no cats have been found in B. Selecting A.* makes sure your not getting the columns from B which are bound to be null anyway.

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