Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

I have two tables, records and data records have multiple fields (first name, last name, etc.). All of these fields is a foreign key for the data table where the actual value is stored. I want to search for multiple record fields.

Below is an example query using INTERSECT, however, I need one that works in MySQL.

SELECT records.id FROM records, data WHERE data.id = records.firstname AND data.value = "john"
INTERSECT
SELECT records.id FROM records, data WHERE data.id = records.lastname AND data.value = "smith"

1 Answer

0 votes
by (12.7k points)

You can use an inner join to filter for rows which have a matching row in the different table:

SELECT DISTINCT records.id 
FROM records
INNER JOIN data d1 on d1.id = records.firstname AND data.value = "john"
INNER JOIN data d2 on d2.id = records.lastname AND data.value = "smith"

One of the various different alternatives is an in clause:

SELECT DISTINCT records.id 
FROM records
WHERE records.firstname IN (
    select id from data where value = 'john'
) AND records.lastname IN (
    select id from data where value = 'smith'
)

Want to be a SQL expert? Enroll in the SQL Training program offered by Intellipaat to learn more and get certified.

Related questions

0 votes
1 answer
asked Jan 6, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Jan 6, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Jan 5, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Jan 5, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer

Browse Categories

...