Question

Sorry for my English

I have two tables:

Partners

ID | NAME | IS_FAVORITE

PartnerPoints

ID | PARTNER_ID | NAME

And I want to get all rows from PartnerPoints which related to Partners (by PARTNER_ID) with the field IS_FAVORITE set to 1. I.e. I want to get all favorite partner points.

How can I do that?

Was it helpful?

Solution

You just need to use a WHERE clause:

SELECT PartnerPoints.*
  FROM PartnerPoints
 WHERE EXISTS ( SELECT *
                  FROM Partners
                 WHERE Partners.ID = PartnerPoints.PARTNER_ID
                   AND Partners.IS_FAVORITE = 1
              )

OTHER TIPS

You can do this by JOINING the tables.

SELECT PartnerPoints.*
FROM PartnerPoints JOIN Partners ON PartnerPoints.Partner_ID=Partners.ID
WHERE Partners.Is_favorite = 1

This is an INNER JOIN. Oscar Pérez’s answer, with the subquery, is called a SEMI-JOIN. The database may execute the same plan, or this INNER JOIN may be faster. In more complicated cases, you may have to use a semi-join.

You can do this by first computing the IDs of all favorite partners, and then searching for PartnerPoints that have such a partner ID:

SELECT *
FROM PartnerPoints
WHERE Partner_ID IN (SELECT ID
                     FROM Partners
                     WHERE Is_Favorite = 1)

Which type of query is fastest depends on the amount and distribution of data in the tables, and of which indexes you have; if the speed actually matters to you, you have to measure all three queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top