简体   繁体   中英

SQL query on multiple tables

Suppose i have the following 2 tables:

Persons Table:  
Name  
ID[Primary Key]

Fruits Table:  
Name  
ID[Foreign Key Persons.ID]

This is a table structure for storing persons and the fruits they like. Now if I want to find all the persons who like "Apple" and "Orange"(this would be dynamic). How can i design a SQL query for that?

You can use a query like the following to get the IDs of all persons who like Apples and Oranges:

SELECT p.ID
FROM Persons AS p
JOIN Fruits AS f ON p.ID = f.PersonsID
WHERE f.Name IN ('Apple', 'Orange')
GROUP BY p.ID
HAVING COUNT(DISTINCT f.Name) = 2

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