SQL从多个表中获取值,然后对其进行排序

时间:2013-08-28 15:35:26

标签: mysql sql

我想做一个MySQL查询。我有4张桌子:A,B,C,D。

我想得到共同的价值:所有4个表中的“胜利”WHERE“account”= 1然后按大多数“胜利”排序。所有订购的“胜利”限制为3。

如果你帮助我,我会很高兴。

我试过这样的事情:

SELECT o.*
FROM (
(SELECT wins FROM 'A')
UNION ALL
(SELECT wins FROM 'B')
UNION ALL
(SELECT wins FROM 'C')
UNION ALL
(SELECT wins FROM 'D')
UNION ALL
(SELECT * FROM 'A'
WHERE
    account=1) 
) AS o
ORDER BY wins DESC

但这确实是错误的。

2 个答案:

答案 0 :(得分:0)

如果您需要知道从中获得结果的表格:

SELECT *
FROM (  SELECT wins, 'Table A' AS DataTable
        FROM TableA
        WHERE account = 1
        UNION ALL
        SELECT wins, 'Table B' 
        FROM TableB
        WHERE account = 1
        UNION ALL
        SELECT wins, 'Table C' 
        FROM TableC
        WHERE account = 1
        UNION ALL
        SELECT wins, 'Table D' 
        FROM TableD
        WHERE account = 1) AS X
ORDER BY wins
LIMIT 3

如果这不重要,您只需要最高的wins

SELECT *
FROM (  SELECT wins
        FROM TableA
        WHERE account = 1
        UNION
        SELECT wins
        FROM TableB
        WHERE account = 1
        UNION
        SELECT wins
        FROM TableC
        WHERE account = 1
        UNION
        SELECT wins
        FROM TableD
        WHERE account = 1) AS X
ORDER BY wins DESC
LIMIT 3

答案 1 :(得分:0)

SELECT o。* FROM A
加入B
加入C
加入D
Daccount = AaccountCaccount = Aaccount
Baccount = Aaccount
Aaccount ='1'
订购者Awins