如何在SELECT中标记表?

时间:2013-09-09 17:27:14

标签: mysql sql select

我尝试从两个表中选择值:


    SELECT id, alife, login
    FROM players
    UNION ALL
    SELECT id, alife, (
        SELECT players.login
        FROM players
        WHERE players.id = id
        LIMIT 0 , 1
    )
    FROM attempts
    ORDER BY `alife`
    LIMIT 0 , 30

如何用表格线标记每一行?如

ID     ALIFE     LOGIN     TABLE
1      100       Any_A     players
4      90        Any_B     players
3      80        Any_C     attempts

由于

2 个答案:

答案 0 :(得分:4)

 SELECT id, alife, login, 'players' as `TABLE`
    FROM players
    UNION ALL
    SELECT id, alife, (
        SELECT players.login
        FROM players
        WHERE players.id = id
        LIMIT 0 , 1
    ), 'attempts' as `TABLE`
    FROM attempts
    ORDER BY `alife`
    LIMIT 0 , 30

答案 1 :(得分:0)

这是要注意您的查询不正确。这一行:

WHERE players.id = id

被解释为:

WHERE players.id = players.id

基于SQL范围规则。

据推测,您需要以下内容:

SELECT id, alife, login, 'players' as which
FROM players
UNION ALL
SELECT id, alife, (SELECT players.login
                   FROM players
                   WHERE players.id = attempts.player_id
                   LIMIT 0 , 1
                  ), 'attempts' as which
FROM attempts
ORDER BY `alife`
LIMIT 0 , 30;

此外,因为子查询没有order by,并且id关系为1-1会有意义,将此作为连接的说法会更清楚:

SELECT id, alife, login, 'players' as which
FROM players
UNION ALL
SELECT a.id, a.alife, p.login, 'attempts' as which
FROM attempts a left outer join
     players p
     on p.id = a.player_id
ORDER BY `alife`
LIMIT 0 , 30;

如果您正在使用大量数据,可以进行其他修改以提高性能。