I have the following sql. I want to be able to pull in a yes/no (true/false) if a subquery returns anything.
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
I want the subquery to return a yes if results returned.
You can use count(*):
SELECT 0 != (SELECT COUNT(*) FROM (subquery))
Which gives you 1 if the subquery returned anything.
For the subquery to return a "yes" if results returned (and empty string if not):
SELECT IF(condition = 1, 'yes', '') AS isTrue FROM table WHERE some_condition_goes_here
That would work if you're joining on some column, which you don't specify in the subquery you showed. The join would go in the WHERE clause replacing "some_condition_goes_here". So something like:
WHERE table.id = some_other_table.tableid
精彩评论