I only know basic SQL but the project that I am working on uses pretty complex queries. There is one query that I can’t understand. The tables and fields of concern are people and person_details and the executable part of an even dirtier query is:
SELECT people.first_name
, people.last_name
, person_statuses.name as person_status
, companies.name as company_name
, person_roles.name as role
, person_role_memberships.event_name as membership_year
, person_role_memberships.start_date as start_date
, person_role_memberships.end_date as end_date
, person_role_memberships.sponsor_parent_company as sponsor_parent_company
, person_role_memberships.former_sponsor_parent_company as former_sponsor_parent_company
, person_role_memberships.workshop as workshop
FROM people
, *person_details as business_details*
, *person_details*
, person_roles
, person_role_memberships
, companies
, person_statuses
, companies as parent_companies
WHERE person_role_memberships.person_id = people.id
AND person_role_memberships.person_role_id = person_roles.id
AND
business_details.type = 'BusinessDetail'
and business_details.person_id = people.id
AND person_details.type = 'PersonalDetail'
and person_details.person_id = people.id
AND people.person_status_id = person_statuses.id
AND ifnull(companies.parent_id, companies.id) = parent_companies.id
AND people.company_id = companies.id
AND companies.name = 'Pak Qatar'
AND people.last_name = 'Aslam'
limit 100;
I want to know what is the logic that the bold part of the where clause is creating. Is it, because of the AND keyword, only allowing those persons, which have BusinessDetail as well as PersonalDetails is the person_details table?
It’s basically saying:
The person MUST have a business_details record which MUST be of type ‘BusinessDetails’ AND the person MUST have a person_details record which MUST be of the type ‘PersonalDetail’ It looks like both are stored in the same table (business_details is an alias of the person_details table), so its joining to the table twice to check for both conditions.
I’m not sure what flavour of SQL this is (SQL Server/Oracle etc) but the query could probably be written out a little neater using proper join syntax (although the syntax used will create joins under the hood, its not as easy to read as something with explicit join syntax).