0

I have two tables with like below codes:

Table: Accounts

id |    username    |   email   |   registered  
1   |   player1     | 123@asd.ad|   2012-05-03  
2   |   goodman     | 1345@bs.ad|   2012-06-03  
3 | goodbat | asdh@asd.d| 2012-06-05  

table:characters

guid    |   account |   name    |   rank  
213     |   1       |   fres    |   2  
214     |   2       |   sdg2    |   3  
215     |   1       |   fgax    |   4  
216     |   3       |   zFvx |  8  
217     |   3       |   zsvx    |   2 
...

I want to show accounts with their highest rank character with just one Query .

output (Show Accounts with their Highest rank character)

username : player1 | 123@asd.ad | char: fgax(4)  
username : goodman | 1345@bs.ad | char: sdg2(3)  
username : goodbat | 134s@bs.ad | char: zFvx(8)  
...

My Query:

SELECT username,email,id FROM accounts
4

5 回答 5

0
SELECT a.username, a.email, a.id, c.name
FROM accounts a 
JOIN chars c ON a.id = c.account 
ORDER BY a.rank DESC
于 2012-07-12T17:39:36.167 回答
0

Try this::

SELECT 
a.username as userName, 
a.email as email, 
a.id as id, 
c.name as name

FROM accounts a 
INNER JOIN chars c ON (a.id = c.accoun)t 
ORDER BY a.rank DESC
于 2012-07-12T17:43:48.553 回答
0

What you need is a table join. What table joins do is that they query 2 tables, in your case Table1 and table2. Here is the query and it will be followed by the explanation.

SELECT `t1`.`username`, `t1`.`email`, `t2`.account 
FROM `Table1` `t1`, `table2` `t2` 
WHERE `t1`.`id` = `t2`.`account` ORDER BY `rank` DESC
LIMIT 0,3

LINE 1: SELECT... t1.username means username column from t1., and so on...and the t1, t2 notation comes from...

LINE 2: FROM... Table1 t1 means I am querying from Table1, and assigned it an alias or pointer t1. This is the same for how we assign table2 to t2.

LINE 3: WHERE... This means that you join the tables based on a common column. In this case, both Table1 and table2 share the same set of values - id for Table1 and account for table2. Hence, you used the above line.

ORDER BY... This means you want to arrange the records based on a certain criteria, in this case rank. There are 2 directions - ASC which means Ascending (smallest top) or DESC which means Descending.

LINE 4: LIMIT 0,3 This means I want to get the first row (0) and only 3 records. Hence, LIMIT 0,3

This is the most comprehensive explanation I could give.

于 2012-07-12T17:58:51.507 回答
0

Try this.

SELECT 
t1.username as userName, 
t1.email as email, 
concat(t2.name, '(', t2.rank, ')') as name
FROM table1 t1 
INNER JOIN table2 t2 ON t1.id = t2.account 
ORDER BY t2.rank DESC
于 2012-07-12T18:11:16.387 回答
0

You can try this:

SELECT a.username, a.email, c.name
FROM Accounts a, characters c
WHERE a.id=c.account
ORDER BY MAX(c.rank) DESC
于 2012-07-12T18:18:44.787 回答