0
PersonId    Name        Category
1           John        Finance
2           Tom         HealthCare
3           Bill        HealthCare

I have this data sctucture. I want to select all people from category by only person id. Example: Input - person id - 2, Next step - category of this person - HealthCare, result - get all people from HealthCare

I know I can do it with 2 queries, but is it possible to do in 1 query?

3 Answers 3

1

This can't be achieved through one Query. You can use Limit 1 in your first query then get its category field and then go for second query.

1

You cannot do it with one query because inner select should not be on the same sObject.

0

You can do it by one query written in constructor that mean it will run just once during page load and second query to select people every time you enter new personId. there by controller will have to use just once query every time user enters new person Id and we can get ris of double writing two queries. But to implement this there is a one limitation we need to keep in mind that number of records should not exceed than 50,000.

So here is how you can do it.

Step 1: Select All the people records from data base(ListOfPeople). step 2: iterate through ListOfPeople and Build a MAP with key as PersonId and value as Category(PIDToCat). step 3: Write a query to fetch the select the people by using the The Map to fetch the category value relevant to PersonId.

So your code will look like as given below In Constructor

Map PidToCat = new map Listofpeople=query all records For(iterate through Listofpeople) PidToCat.add(people.PersonId,People.Category)

In Search Method

PId=PersonId entered in input text by user select People for that category =[select Name from people where category =PidToCat.get(PId)]

1
  • I cannot load all records because it will be not effective, I need this to me with best performance possible. Commented Mar 28, 2016 at 12:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .