retrive second highest point from table with no unique column - php

i have one table named users. In this table i have one column named credits(not unique).
Now i want the second highest user accroding to the users credits. If the credits field is unique thenmy below query is working fine
SELECT * FROM users ORDER BY credits DESC LIMIT 1 , 1
But , if the users credit is not unique then its create problem for retrive me data
suppose,
mack has 200 credits
jack has 200 credits
rock has 150 credits
when i has this types of record then,in output of this query i want the rock record not jack
can anyone help me to find out the correct value ?
thanks in advance

SELECT a.*
FROM users a
INNER JOIN
(
SELECT DISTINCT credits
FROM users
ORDER BY credits desc
LIMIT 1,1
) b ON a.credits = b.credits
SQLFiddle Demo

Hope this helps (first get second highest credits then find the users having those that credit andselect one from the top`. This will retrieve one user having second highest credit):
SELECT * FROM users
WHERE credits = (SELECT distinct credits FROM users
ORDER BY credits DESC LIMIT 1,1)
LIMIT 1;
EDIT: If you also want to select within users having same score then use the appropriate filter/sorting condition e.g. to select rock between rock and jenni, you could have another ordering base on name(assuming name is the column having names)
SELECT * FROM users
WHERE credits = (SELECT distinct credits FROM users
ORDER BY credits DESC LIMIT 1,1)
ORDER name desc
LIMIT 1;
To get both rock and jenni, just remove the limit from the end and update the inner limit e.g:
SELECT * FROM users
WHERE credits = (SELECT distinct credits FROM users
ORDER BY credits DESC LIMIT 1, 1);

try this
Select * FROM users
Where Credits < (Select Max(Credits) From Users)
ORDER BY credits DESC LIMIT 1;

Related

Select from 3 tables with calculating

I try to make a query in MySQL that gets data from 3 tables, and calculate in 2 tables. But i really don't know how to do this.
I have this in my PHP code to calculate "Avage Cost per Click":
Get all the campaigns.
SELECT * FROM campaigns;
Get how many clicks the campaign has:
select SUM(id) as IALT2 from aktivitet where annonce_id = '##CAMPAIGN_ID' group by ip");
Get the total revenure from all rows
SELECT SUM(price) as IALT from money where ad = '##CAMPAIGN_ID' group by id
Now i can calculate the "Avage Cost Per Click"
"IALT / IALT2" = CPC
then it should say:
select * from campaign order by CPC desc limit 0,1
select * from campaigns C
order by
(
(select SUM(price) from money where ad = C.CAMPAIGN_ID)
/
(select SUM(id) from aktivitet where annonce_id = C.CAMPAIGN_ID)
)desc limit 0,1
just guessing, but I think you want this

select 3 rows from mysql table, then get each row's specific column

Select 3 rows from table1
Get a specific column data out of each row.
Then use that each column data obtained , to make a query again to get data from table2.
Store the data obtained in step 4 into a variable for each row.
Then put them in json array (table 1 , 3 rows + table 2's data(each of them).
I am building a rank table, it displays top 3 users with their rank name.
For example:
User1 has 2000 points , user 2 has 4000points , user 3 has 10k points , so the top 3 user is :
user 3 > user 2 > user 1
So , i want the php to go to 'users' table and get the top 3 members using this:
$query = mysql_query("SELECT * FROM users ORDER BY pts DESC LIMIT 3");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
Table structure for 'user':
1.username(varchar)
2.pts(int)
After the rows are put into an array , how can i get 'points' for each of the row in that array.
Then go to 'rank' table to get their ranknames.
Table structure for 'rank':
1.rank(varchar)
2.pts(int)
Inside rank table there is 'pts' to let php choose compare which rank the user is at based on the points from each row of the array.
Normally i would use this if its only for 1 user , but for multiple users , im not sure:
$result = mysql_query("SELECT * FROM rank WHERE pts <= '$upts' ORDER BY pts DESC LIMIT 1")
or die(mysql_error());
Then after getting the rank for the top 3 users , php will now add the ranks to each of the user(row) in that array(of course , add it to the rank owner, not just simply place it in).
Then JSON encode it out.
How can i do this?
I am not sure if this is what you want. That is combine the two query into one query. Please take a look at http://sqlfiddle.com/#!2/ad419/8
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts group by user.id
UPDATED:
For extracting top 3, could do as below;
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts
GROUP BY user.id
ORDER BY pts DESC LIMIT 3
If i understand correctly, you need to get values from Rank and Users tables. In order to do that in just one query You need to add FK (Foreign Key) to the Rank table that points to a specific user in the Users table.
So you need to add userId to the Rank table and then you can run:
SELECT r.rank, u.points from users u,rank r where u.userId = r.userId
This is roughly what you need.
Not quite the answer to your exact question, but this might be of use to you: How to get rank using mysql query. And may even mean that you don't require a rank table. If this doesn't help, I'll check back later.
Use this query
$query = "SELECT
u.pts,
r.rank
FROM users as u
left join ranks as r
on r.pts = u .pts
ORDER BY pts DESC
LIMIT 3";
This will bring what you required without putting into an array
$rec = mysql_query($query);
$results = arrau();
while($row = mysql_fetch_row($rec)){
$results[] = $row;
}
echo json_encode($results);
It looks like what you're trying to do is retrieve the rank with the highest point requirement that the user actual meets, which isn't quite what everyone else is giving here. Fortunately it is easily possible to do this in a single query with a nice little trick:
SELECT
user.username,
SUBSTRING_INDEX(GROUP_CONCAT(rank.rank ORDER BY pts DESC),",",1) AS `rank`
FROM user
LEFT JOIN rank ON user.pts >= rank.pts
GROUP BY user.id
ORDER BY pts DESC
LIMIT 3
Basically what the second bit is doing is generating a list of all the ranks the user has achieved, ordering them by descending order of points and then selecting the first one.
If any of your rank names have commas in then there's another little tweak we need to add on, but I wouldn't have thought they would so I've left it out to keep things simple.

PHP / MySQL - Getting last 3 uniquely updated records

Im wondering if someone could help out.
I need to write a query that gets the last 3 'created' records, but their UID has to be unique so for example, my mysql fields look like so
uid created
19 2012-02-01 01:08:43
18 2012-02-31 17:07:21
19 2012-02-31 16:07:20
20 2012-02-31 13:03:00
Ok, so i want to get the last 3 uid's created ... but they have to be unique uid's so the same uid cant appear twice.
Cheers
this should do this
SELECT * FROM ( SELECT * FROM tablename ORDER BY uid, created DESC ) ordered GROUP BY uid
You can select last 3 IDs with this query:
SELECT * FROM ( SELECT * FROM table ORDER BY uid, created DESC ) AS selected GROUP BY uid LIMIT 3
Logic is: order table by uid field in descending and limit to 3 fields.
Use a Distinct and Group by to get what you're after:
SELECT DISTINCT * FROM table GROUP BY uid;
That will give you all unique UID's.
Then add your ORDER BY in there to make sure you grab the last records.
SELECT *
FROM table
ORDER BY created DESC
GROUP BY uid LIMIT 0,3
SELECT uid
, MAX(created) AS max_created
FROM tableX
GROUP BY uid
ORDER BY max_created DESC
LIMIT 3

PHP / MySQL Checking data between tables with long query

This is a more detailed question as my previous attempt wasn't clear enough. I'm new to MySQL and have no idea about the best way to do certain things. I'm building a voting application for images and am having trouble with some of the finer points of MySQL
My db
_votes
id
voter_id
image_id
_images
id
file_name
entrant_id
approved
_users
id
...
Basically I need to do the following:
tally up all votes that are approved
return the top 5 with the most votes
check if the user has voted on each of these 5 (return Boolean) from another table
I've tried variations of
SELECT i.id, i.file_name, i.total_votes
FROM _images i WHERE i.approved = 1
CASE WHEN (SELECT count(*) from _votes v WHERE v.image_id = i.id AND v.voter_id = ?) > 0 THEN '1' ELSE '0' END 'hasvoted'
ORDER BY i.total_votes DESC LIMIT ".($page*5).", 5
is that something I should try and do all in one query?
This query was working fine before I tried to add in the 'hasvoted' boolean:
SELECT id, file_name, total_votes FROM _images WHERE approved = 1 ORDER BY total_votes DESC LIMIT ".($page*5).", 5
At the moment I'm also storing the vote count in the _images table and I know this is wrong, but I have no idea about how to tally the votes by image_id and then order them.
Let me give this a shot to see if I understand your question:
SELECT i.*,(SELECT COUNT(*) FROM _votes WHERE i.id = image_id) AS total_votes, (SELECT count(*) from _votes where i.id = image_id and user_id = ?) as voted FROM _images AS i WHERE i.approved = 1

MySQL query: generate a report of the top votes for the each food type

I have a user table with id, username and food_id columns. The idea is the user stored their favorite food and we come up with a league table of foods and I want to generate a report of the top votes for the each food type. I am using MySQL and PHP.
For clarity, here is an example of the table:
id food_id username
1 1 Bob
2 100 Jane
3 200 Andy
4 1 Maggy
5 100 Rich
6 100 Mick
7 1 Kevin
How do I write the query to list the foods that have the most votes. I want to limit the result to x number, say top 100. In this case I want the result to be as follows:
food_id score
1 3
100 4
I hope the question is clear enough. The query is beyond me but I am sure it must be possible to do it using DISTINCT and COUNT in some way or other. Perhaps it's sub queries?
select food_id, count(*) score
from myTable
group by food_id
order by score desc limit 100
SELECT F.food_name,
COUNT(*) AS score
FROM myTable AS M
INNER JOIN food_table AS F
ON F.food_id = M.food_id
GROUP BY F.food_name
ORDER BY score DESC limit 100
select count(*) as top100 from table group by food_id order by top100 desc limit 100
SELECT f.`food_id`, COUNT(*) AS `count`
FROM `fav_food_table` f
GROUP BY f.`food_id`
ORDER BY `count` DESC
LIMIT 100;

Categories