简体   繁体   中英

Return SQL subquery as boolean field?

I would like to do something like this (mix of sql with pseudocode):

let's assume for this example that there is a separate phone number table:

person: person_id, person_name, person_lastName
phone_number: phonenmb_id, phonenmb_number, phonenmb_person_id

SELECT p.name, p.lastName, hasPhoneNumber = hasPhoneNumber(someNumber)

In the example i would like to get some data from a person, and given a certain phone number, return TRUE if the person has that number on it's number list, or FALSE if it doesn't.

If anyone can provide a hint on how to do this directly with Doctrine and DQL it'd be awesome, otherwise i'll just translate it to DQL myself.

One approach is to outer join to the phone number table using the person_id and the phone number, and then check if the outer join was satisfied to calculate the boolean.

Example using your schema:

SELECT p.person_name, p.person_lastName, 
  (pn.phonenmb_id IS NOT NULL) as hasPhoneNumber
FROM person p
  LEFT OUTER JOIN phone_number pn on pn.phonenmb_person_id = p.person_id 
                                 and pn.phonenmb_number = someNumber
GROUP BY p.person_name, p.person_lastName

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