2011-06-21 142 views
0

我有以下的sql。如果子查询返回任何内容,我希望能够引入yes/no(真/假)。如果mysql中的isnull选择语句

SELECT 
       post.topic_id, 
       topic.topic_posts, 
       topic.topic_title, 
       topic.topic_poster_name, 
       topic.topic_last_post_id, 
       topic.topic_start_time, 
       (SELECT post_time FROM bb_posts WHERE post_id = topic.topic_last_post_id) as last_post_time, 
       topic.topic_slug, 
       topic.topic_posts, 
       `group`.name AS group_name, 
       `group`.slug AS child_slug, 
       `parent`.slug AS parent_slug, 
         (SELECT id FROM table WHERE condition = 1) as isTrue << subquery 
      FROM bb_posts post 
      LEFT JOIN bb_topics topic 
       ON topic.topic_id = post.topic_id 
      LEFT JOIN bb_forums forum 
       ON topic.forum_id = forum.forum_id 
      LEFT JOIN wp_bp_groups_groupmeta groupmeta 
       ON forum.forum_id = groupmeta.meta_value 
      LEFT JOIN wp_bp_groups `group` 
       ON groupmeta.group_id = `group`.id 
      LEFT JOIN wp_bp_groups `parent` 
       ON `group`.parent_id = `parent`.id 
      $conditions 
      GROUP BY topic_id 
      ORDER BY $sort_col $dir 
      LIMIT $offset,$num 

我希望子查询返回一个yes如果结果返回。

回答

2

您可以使用count(*):

SELECT 0 != (SELECT COUNT(*) FROM (subquery))

,让你1,如果子查询返回的任何东西。

+0

我怎样才能在子查询的WHERE条件post.topic_id。从你的例子来看,你似乎是两次嵌套子查询。我不能从父查询post.topic_id。 – madphp

0

子查询返回一个“是”,如果返回的结果(而空,如果没有):

SELECT IF(condition = 1, 'yes', '') AS isTrue FROM table WHERE some_condition_goes_here 

,如果你加入了一些列,你不指定将工作你展示的子查询。连接将在WHERE子句中替换“some_condition_goes_here”。所以像这样:

WHERE table.id = some_other_table.tableid