i'm pulling my hair out here:
I have a sql statement that is part of an ajax call:
SELECT $wpdb->commentmeta.meta_value, $wpdb->comments.comment_ID, $wpdb->comments.comment_date, $wpdb->comments.user_id, $wpdb->comments.comment_content, $wpdb->comments.comment_author
FROM $wpdb->commentmeta
JOIN $wpdb->comments ON $wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id
WHERE $wpdb->commentmeta.meta_key = '_commentsvote'
AND $wpdb->comments.comment_date >='" . $current_year . "-" . $current_month . "-01'
AND $wpdb->comments.comment_date <='" . $current_year . "-" . $current_month . "-31'
ORDER BY $wpdb->commentmeta.meta_value DESC
the statement works great, and returns results, however, the order is off. now, i know this is because the meta_value is actually a varchar, and not an int. so, the internets told me to do either a convert or cast:
Convert:
SELECT $wpdb->commentmeta.meta_value, $wpdb->comments.comment_ID, $wpdb->comments.comment_date, $wpdb->comments.user_id, $wpdb->comments.comment_content, $wpdb->comments.comment_author
FROM $wpdb->commentmeta
JOIN $wpdb->comments ON $wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id
WHERE $wpdb->commentmeta.meta_key = '_commentsvote'
AND $wpdb->comments.comment_date >='" . $current_year . "-" . $current_month . "-01'
AND $wpdb->comments.comment_date <='" . $current_year . "-" . $current_month . "-31'
ORDER BY CONVERT(INT, $wpdb->commentmeta.meta_value) DESC
CAST
SELECT $wpdb->commentmeta.meta_value, $wpdb->comments.comment_ID, $wpdb->comments.comment_date, $wpdb->comments.user_id, $wpdb->comments.comment_content, $wpdb->comments.comment_author
FROM $wpdb->commentmeta
JOIN $wpdb->comments ON $wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id
WHERE $wpdb->commentmeta.meta_key = '_commentsvote'
AND $wpdb->comments.comment_date >='" . $current_year . "-" . $current_month . "-01'
AND $wpdb->comments.comment_date <='" . $current_year . "-" . $current_month . "-31'
ORDER BY CAST($wpdb->commentmeta.meta_value AS INT) DESC
I keep getting sql errors on both of these when i run it as a sql statement (obviously, i convert the $wpdp to just say wp_) out of wordpress. the error is non specific - i.e. "you have an error near as int" for example.
so, two questions, first one is wp specific, and the second is a sql:
- i'm pretty sure there's a way to write all this as an arg array i can pass into wp_query, but i'm unsure of how to do a join. code examples here would be super helpful.
- why why WHY is this sql statement unwilling to convert that last colomn to an int?
Thanks Wp and SQL geniuses for reading!