如果子查询存在,则显示行

时间:2012-02-07 13:09:01

标签: mysql sql

如果子查询中的任何一个返回一个字段,我想只返回一行。

SELECT upd8r_user_accts.id, (

SELECT fb_id
FROM upd8r_facebook_accts
WHERE user_id = upd8r_user_accts.id
) as facebook, (

SELECT twitter
FROM upd8r_twitter_accts
WHERE user_id = upd8r_user_accts.id
) as twitter
FROM  `upd8r_user_accts` 

我也会为每个子查询返回id / access标记值 - 我怎么能返回布尔值yes或no?

4 个答案:

答案 0 :(得分:4)

SELECT
  upd8r_user_accts.id,
  upd8r_facebook_accts.fb_id  IS NOT NULL  AS has_fb_id,
  upd8r_twitter_accts.twitter IS NOT NULL  AS has_twitter
FROM
  upd8r_user_accts
LEFT JOIN
  upd8r_twitter_accts
    ON upd8r_twitter_accts.user_id = upd8r_user_accts.id
LEFT JOIN
  upd8r_facebook_accts
    ON upd8r_facebook_accts.user_id = upd8r_user_accts.id
WHERE
     upd8r_facebook_accts.fb_id  IS NOT NULL
  OR upd8r_twitter_accts.twitter IS NOT NULL

答案 1 :(得分:1)

试试这样:

SELECT u.id, f.fb_id as facebook, t.twitter as twitter
FROM  upd8r_user_accts u
LEFT JOIN upd8r_facebook_accts f on f.user_id = u.id
LEFT JOIN upd8r_twitter_accts t on t.user_id = u.id

现在,如果你想在facebook和twitter中使用yes或no,请按照以下步骤操作:

SELECT u.id,
       case when f.fb_id is null then 'no' else 'yes' end as facebook,
       case when t.twitter is null then 'no' else 'yes' as twitter
FROM  upd8r_user_accts u
LEFT JOIN upd8r_facebook_accts f on f.user_id = u.id
LEFT JOIN upd8r_twitter_accts t on t.user_id = u.id

答案 2 :(得分:0)

您需要做的是检查相应表格中是否有一行:

    SELECT upd8r_user_accts.id
           ,(SELECT fb_id
             FROM upd8r_facebook_accts
             WHERE user_id = upd8r_user_accts.id) as facebook
           ,(SELECT twitter
             FROM upd8r_twitter_accts
             WHERE user_id = upd8r_user_accts.id) as twitter
    FROM  upd8r_user_accts
    WHERE EXISTS (SELECT fb_id
                  FROM upd8r_facebook_accts
                  WHERE user_id = upd8r_user_accts.id) 
          OR
          EXISTS (SELECT twitter
                  FROM upd8r_twitter_accts
                  WHERE user_id = upd8r_user_accts.id)

答案 3 :(得分:0)

作为左连接的替代方法,尝试使用内联接到联合集:

select u.id, 
       coalesce(max(a.fb_id), 'no') fb_id, 
       coalesce(max(a.twitter), 'no') twitter
from
(select id, 'yes' fb_id, null twitter from upd8r_facebook_accts
 union all
 select id, null fb_id, 'yes' twitter from upd8r_twitter_accts) a
join upd8r_user_accts u on a.id = u.user_id
group by a.id