查询来自多个表的记录并确定它们来自哪个表

时间:2014-04-12 13:16:43

标签: php mysql

我试图从多个表中获取数据,以便我可以确定它来自哪个表。我想我已经关闭了,但是以下的sql并没有退出工作:

SELECT name, id
AS player FROM players
WHERE name LIKE '%str%'
UNION ALL
SELECT name, id
AS team FROM teams
WHERE name LIKE '%str%'

以下是我得到的结果(作为php assoc数组)。请注意,对于第2项,id的键是播放器,但它应该是团队。

(
[0] => Array
    (
        [name] => Some string
        [player] => 1
    )

[1] => Array
    (
        [name] => Some other string 
        [player] => 2
    )

[2] => Array
    (
        [name] => string
        [player] => 2  // THE KEY HERE SHOULD BE TEAM
    )
)

2 个答案:

答案 0 :(得分:2)

使用unionunion all加入多个查询时,只会考虑第一个查询的列名(或别名)。您可以通过添加假列和类型的硬链字符串来解决此问题。 E.g:

SELECT name, id, 'player' AS type
FROM players
WHERE name LIKE '%str%'
UNION ALL
SELECT name, id, 'team' AS type
FROM teams
WHERE name LIKE '%str%'

使用您的样本日期,此查询将产生以下结果:

(
[0] => Array
    (
        [name] => Some string
        [id] => 1
        [type] => player
    )

[1] => Array
    (
        [name] => Some other string 
        [id] => 2
        [type] => player
    )

[2] => Array
    (
        [name] => string
        [id] => 2
        [type] => team
    )
)

现在,您可以轻松区分结果中的玩家和团队。

答案 1 :(得分:1)

从“tblname”列,您可以识别表格的名称。

SELECT name, id AS player,'players' as tblname FROM players WHERE name LIKE '%str%' 
UNION ALL 
SELECT name, id AS team,'teams' as tblname FROM teams WHERE name LIKE '%str%'