在此查询之后:
SELECT forum_categories.id AS category_id, forum_categories.title, forum_topics.id AS topic_id, forum_topics.title, user
FROM forum_categories JOIN forum_topics ON forum_categories.id=forum_topics.category_id
LEFT OUTER JOIN forum_views ON forum_topics.id=forum_views.topic_id
WHERE forum_categories.id=6
ORDER BY forum_categories.id
我得到了这个结果:
现在,我想:
所以在下面的例子中,结果必须是1行:
6 Welcome (some topic_id) (some title) (djfonplaz or null) 0
并且,如果所有用户都与NULL不同:
6 Welcome (some topic_id) (some title) (djfonplaz) 1
如何在MySql上执行此操作?
答案 0 :(得分:4)
SELECT
forum_categories.id AS category_ids
, forum_categories.title as titles
, forum_topics.id AS topic_ids
, forum_topics.title as topic_titles
, count(*) as NumberOfRows
, GROUP_CONCAT(IFNULL(user,'(no user)')) AS users
, (count(*) - count(user)) as IsThereANull
FROM forum_categories
INNER JOIN forum_topics ON forum_categories.id=forum_topics.category_id
LEFT OUTER JOIN forum_views ON forum_topics.id=forum_views.topic_id
WHERE forum_categories.id=6
GROUP BY category_id
ORDER BY forum_categories.id
IsThereANull将0
没有空,如果有,则为1或更多。
答案 1 :(得分:1)
我认为以下查询应该得到您正在寻找的结果:
SELECT forum_categories.id AS category_id, forum_categories.title,
forum_topics.id AS topic_id, forum_topics.title, user,
(
SELECT MAX(IF(COUNT(*), 0, 1))
FROM forum_categories JOIN forum_topics ON
forum_categories.id=forum_topics.category_id
LEFT OUTER JOIN forum_views ON forum_topics.id=forum_views.topic_id
WHERE forum_categories.id=6 AND user IS NULL
) AS thereIsANull
FROM forum_categories JOIN forum_topics ON forum_categories.id=forum_topics.category_id
LEFT OUTER JOIN forum_views ON forum_topics.id=forum_views.topic_id
WHERE forum_categories.id=6 AND user IS NOT NULL
GROUP BY user
ORDER BY forum_categories.id
答案 2 :(得分:1)
我认为这样的事情可以按照你的意愿行事:
SELECT cat.id AS category_id,
cat.title,
top.id AS topic_id,
top.title,
user,
(
(
SELECT COUNT(*) FROM forum_categories
WHERE id = cat.id AND user IS NULL
) > 0 -- This is to check wether if any NULL is found
) as thereIsANull
FROM forum_categories as cat
JOIN forum_topics as top ON cat.id = top.category_id
LEFT OUTER JOIN forum_views as view ON top.id = view.topic_id
WHERE cat.id = 6 -- You can ofcourse change this to whatever variable your using
GROUP BY cat.id -- Just an ordinary group by category id
ORDER BY cat.id
假设在forum_categories表中找到了字段用户,那么只需修改子查询以加入从中获取用户的表
请注意,Thiis与Cez写的基本相同,所以他应该得到一些信用,唯一的区别是子查询和按类别ID而不是用户分组。
尝试一下,让我知道它是否正确:)