複数のテーブルからデータを取得する必要があります。今のところ、それらの最大値を取得しています
_ SELECT disc.id,
users.user_login as 'last_active_user',
disc.discussion_sub,
list.todo_list_title,
todo.todo_title,
count(comments.comment),
MAX(CAST(comments.comment_posted AS CHAR))
FROM abc_discussions as disc
LEFT OUTER JOIN abc_todo_list as list
ON disc.comment_table_type = 'todo_list' AND disc.comment_table_id = list.id
LEFT OUTER JOIN abc_todo as todo
ON disc.comment_table_type = 'todo_item' AND disc.comment_table_id = todo.id
LEFT OUTER JOIN abc_users as users
ON users.user_id = 2
LEFT OUTER JOIN abc_comments as comments
ON disc.id = comments.discussion_id
GROUP BY disc.id
_
ここで、$last_comment_by->user_id = $wpdb->get_row("SELECT user_id FROM abc_comments ORDER BY comment_posted DESC LIMIT 1" )->user_id;
単一のクエリにする方法はありますか?
私は試した
_SELECT a.id ,
a.discussion_sub,
b.todo_list_title,
c.todo_title,
ANY_VALUE(q.user_login) as 'last_active_user',
count(comment),
MAX(comment_posted)
FROM abc_discussions a
LEFT JOIN abc_todo_list b
ON a.comment_table_type = 'todo_list' AND a.comment_table_id = b.id
LEFT JOIN abc_todo c
ON a.comment_table_type = 'todo_item' AND a.comment_table_id = c.id
LEFT JOIN (
SELECT x.user_id as user_id, y.discussion_id as discussion_id
FROM abc_users x
LEFT OUTER JOIN abc_comments y
ON x.user_id = y.user_id ) d
ON d.discussion_id = a.id
LEFT OUTER JOIN abc_users q
ON q.user_id = d.user_id
LEFT JOIN abc_comments e
ON a.id = e.discussion_id
GROUP BY a.id
_
しかし、user_loginとコメント数の結果が間違っています。
「last_active_user」は次のように聞こえます
_( SELECT user_login FROM users WHERE ... ORDER BY ... DESC LIMIT 1 )
_
count(comments.comment)は次のように聞こえます
_( SELECT COUNT(*) FROM abc_comments WHERE ... )
_
つまり、結合を取り除き、上記のように集計値をサブクエリに置き換えます。
JOIN
は行数を分解し、
GROUP BY
_が必要ですCOUNT
は数が多すぎますuser_login
_にないアイテム(_GROUP BY
_など)は、予測できない値になります。(はい、MAX(comment_posted)
はMAX(CAST(comments.comment_posted AS CHAR))
と同じですが、単純です。)
このようなものはどうですか:
SELECT a.id
, user_login as 'last_active_user'
, discussion_sub
, todo_list_title
, todo_title
, count(comment)
, MAX(CAST(comment_posted AS CHAR))
FROM abc_discussions a
LEFT JOIN abc_todo_list b ON comment_table_type = 'todo_list' AND comment_table_id = b.id
LEFT JOIN abc_todo c ON comment_table_type = 'todo_item' AND comment_table_id = c.id
LEFT JOIN
( SELECT x.*
FROM abc_users x
INNER JOIN abc_comments y ON y.user_id = x.id) d on 1 = 1 -- or however you wish to join this to the rest of your query
LEFT JOIN abc_comments e ON a.id = e.discussion_id
GROUP BY a.id
, user_login
, discussion_sub
, todo_list_title
, todo_title