![](/img/trans.png)
[英]mysql join query for select rows from two tables that one table is having multiple rows matching to the first table
[英]MySQL Select From Two Table per Rows of First Query
我有兩個表,如下所示:
表:帳戶
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
桌子:字符
guid | account | name | rank
213 | 1 | fres | 2
214 | 2 | sdg2 | 3
215 | 1 | fgax | 4
216 | 3 | zFvx | 8
217 | 3 | zsvx | 2
...
我只想通過一個Query顯示具有最高排名字符的帳戶。
輸出 (顯示具有最高排名字符的帳戶)
username : player1 | 123@asd.ad | char: fgax(4)
username : goodman | 1345@bs.ad | char: sdg2(3)
username : goodbat | 134s@bs.ad | char: zFvx(8)
...
我的查詢:
SELECT username,email,id FROM accounts
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
嘗試這個::
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
您需要的是表聯接。 表聯接的作用是查詢2個表(在您的情況下為Table1和table2) 。 這是查詢,后面將進行解釋。
SELECT `t1`.`username`, `t1`.`email`, `t2`.account
FROM `Table1` `t1`, `table2` `t2`
WHERE `t1`.`id` = `t2`.`account` ORDER BY `rank` DESC
LIMIT 0,3
第1行:SELECT ... t1
。 username
表示t1
username列,依此類推...而t1
, t2
表示法則來自...
第2行:FROM ... Table1
t1
表示我正在從Table1查詢,並為其分配了別名或指針t1
。 這與將table2分配給t2
。
第3行:WHERE ...這意味着您基於一個公共列聯接表。 在這種情況下,無論是Table 1和表2共享同一組值- ID為表1和賬戶表2。 因此,您使用了上面的行。
ORDER BY ...這意味着您要基於某種條件(在這種情況下為排名)排列記錄。 有2個方向-ASC表示上升(最小的頂部)或DESC表示下降。
第4行:LIMIT 0,3這意味着我想獲取第一行(0)和3條記錄。 因此,LIMIT 0,3
這是我能給出的最全面的解釋。
嘗試這個。
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
您可以嘗試以下方法:
SELECT a.username, a.email, c.name
FROM Accounts a, characters c
WHERE a.id=c.account
ORDER BY MAX(c.rank) DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.