MySQL - Order results by relevancy, LEFT JOINS and more

Posted by XaviEsteve on Stack Overflow See other posts from Stack Overflow or by XaviEsteve
Published on 2010-05-18T15:05:59Z Indexed on 2010/05/18 15:10 UTC
Read the original article Hit count: 269

Filed under:
|
|

Hi guys,

I am trying to get some results ordered by total votes (where client votes count 2 points and other people votes are 1 point).

tab_names:

+-----------+
| Name | id |
+------+----+
| John |  1 |
| Paul |  2 |
+------+----+

tab_votes:

+--------+-----------+
| idname | ip        |
+--------+-----------+
|      2 | 127.0.0.1 |
|      2 | 127.0.0.1 |
|      2 | 82.23.5.1 |
|      1 | 127.0.0.1 |
+--------+-----------+

This is the MySQL query I've got but doesn't work:

SELECT *
 COUNT(v.idname) AS totalvotes,
 (SELECT COUNT(v.ip) FROM tab_votes WHERE v.ip LIKE '$ip') AS uservotes
FROM tab_names n 
LEFT JOIN tab_votes v ON n.id = v.idname
GROUP BY n.name
ORDER BY uservotes DESC, totalvotes DESC
LIMIT 40

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql