简体   繁体   中英

MYSQL: Using outer query values in subquery

I have this...

SELECT 
distinct FN.field_first_name_value, 
LN.field_last_name_value,   
u.mail, 
IFNULL(
     (SELECT 'Yes'
          FROM user_roles SUR, users u
       WHERE SUR.uid = u.uid
         AND SUR.rid = 3
       LIMIT 1
     )
   ,'No') AS 'Paying Member'
FROM
users u, 
field_data_field_first_name FN, 
field_data_field_last_name LN, 
role R,
users_roles SUR
where 
u.uid = FN.entity_id 
AND 
u.uid = LN.entity_id
AND 
sur.uid = u.uid
AND 
sur.rid = R.rid

but I want to use the the u.uid in the sub query so that it makes the queries for each row.

How do I include the u.uid from the outer query into the sub query?

Thank You.

You should really learn some better habits of writing queries:

  • Use proper join syntax
  • Do not use single quotes for column aliases
  • Use the minimum number of tables necessary

But, the answer to your question is simply to remove the users table from the correlated subquery:

coalesce((SELECT 'Yes'
          FROM user_roles SUR
          WHERE SUR.uid = u.uid AND SUR.rid = 3
          LIMIT 1
         ), 'No') AS `Paying Member`

Your overall query should probably look more like this:

SELECT FN.field_first_name_value, LN.field_last_name_value, u.mail, 
       COALESCE((SELECT 'Yes'
                 FROM user_roles SUR
                 WHERE SUR.uid = u.uid AND SUR.rid = 3
                 LIMIT 1
                ), 'No') AS `Paying Member`
FROM users u JOIN
     field_data_field_first_name FN
     ON u.uid = FN.entity_id JOIN
     field_data_field_last_name LN
     ON u.uid = LN.entity_id;

The roles and user_roles tables appear to be serving no use in the outer query (although they might be used for filtering, I am guessing this is not the case).

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