Tenho 2 tabelas:
comments_table
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`media_id` int(11) unsigned DEFAULT NULL,
`user_id` int(11) unsigned DEFAULT NULL,//user who commented
`title` varchar(300) DEFAULT NULL,
`url` varchar(300) DEFAULT NULL,
`c_date` datetime,
`comment` longtext DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `media_id` (`media_id`)
id comment user_id
1 foo 1
2 bla 2
3 something 7
votes_table
`comment_id` int(11) unsigned DEFAULT NULL,
`user_id` int(11) unsigned DEFAULT NULL,//user who voted
`vote` tinyint(1) DEFAULT 0,
INDEX `comment_id` (`comment_id`)
comment_id user_id vote
1 2 1
2 4 -1
3 7 0
3 1 1
2 1 1
Tenho 2 dúvidas (obter todos os comentários):
$comments = $wpdb->get_results($wpdb->prepare("SELECT ct.id, ct.comment, ct.user_id, ct.user_display_name, ct.avatar, ct.c_date, SUM(DISTINCT vt.vote) AS vote
FROM $comments_table as ct
LEFT JOIN $votes_table vt on ct.id = vt.comment_id
WHERE ct.media_id=%d
GROUP BY ct.id
ORDER BY ct.c_date DESC", $media_id), ARRAY_A);
Obter comentários onde o usuário votou:
$user_votes = $wpdb->get_results($wpdb->prepare("SELECT vote, comment_id
FROM $votes_table
WHERE user_id=%d", $user_id), ARRAY_A);
Isso funciona como esperado. Há como fazer isso em uma consulta? (por motivos de desempenho)
Por exemplo, adicione aos resultados user_vote = votes_table.vote a comment_table.id votes_table.user_id votado.
Use
MAX(vt.user_id = %d)
para determinar se alguma dasvotes_table
linhas é do usuário especificado. O valor de uma comparação é 1 para TRUE ou 0 para FALSE, entãoMAX()
determinará essa existência.