-2

我有一个表格,其中包含两支球队之间足球比赛的结果。首先,我想要一个团队的下拉菜单。这应该很简单,例如 SELECT * FROM table GROUP BY Team_A

但是如果他们只出现在 Team_B 列中,则可能会错过一个团队。是否可以对列 Team_A 和 Team_B 进行分组,以便我可以在两列中输出所有独特的团队?

4

4 回答 4

3

如果您想要所有名称,请使用union. 这也删除了重复项:

select TeamA from table union
select TeamB from table
于 2013-06-04T13:20:45.113 回答
2

这将为您提供正确的数据,但是 . . .

select team_a as team_name
from test
union
select team_b
from test
order by team_name;

您可能应该有对团队表的外键引用。如果你有这个,对团队名称有强制性的唯一约束,你只需要

select team_name
from teams
order by team_name;
于 2013-06-04T13:21:59.233 回答
0

你不是说:

group by Team_A, Team_B

?

这将按 Team_A 和 Team_B 的组合进行分组

编辑:以两列结束,每列都有一个独特的团队列表,该列表已经存在于该列中(完全如 OP 所述):

SELECT a.*, b.* FROM
(SELECT Team_A, @ida := ifnull(@ida,0) + 1 AS ida FROM table GROUP BY Team_A) AS a
LEFT JOIN
(SELECT Team_B, @idb := ifnull(@idb,0) + 1 AS idb FROM table GROUP BY Team_B) AS b
ON a.ida=b.idb
and isnull(@ida := null) and isnull(@idb := null) -- reset @ida and @idb

UNION ALL -- turn the left and right join into full outer join

SELECT c.*, d.* FROM
(SELECT Team_A, @idc := ifnull(@idc,0) + 1 AS idc FROM table GROUP BY Team_A) AS c
RIGHT JOIN
(SELECT Team_B, @idd := ifnull(@idd,0) + 1 AS idd FROM table GROUP BY Team_B) AS d
ON c.idc=d.idd
and isnull(@idc := null) and isnull(@idd := null) -- reset @idc and @idd
WHERE c.idc is null -- prevent doubles in the full outer join
于 2013-06-04T13:19:31.570 回答
0

使用UNION这样的:

SELECT Team_A AS TeamName FROM table
UNION ALL
SELECT Team_B AS TeamName FROM table

获得不同的团队列表。但我不得不说,你真的需要重组你的数据库。你应该有一个这样的表:

CREATE TABLE Teams (
    ID INT PRIMARY KEY IDENTITY(1, 1),
    Name VARCHAR(50) NOT NULL UNIQUE
)

然后是这样的表:

CREATE TABLE Scores (
    ID INT PRIMARY KEY IDENTITY(1, 1),
    HomeTeamId INT NOT NULL,
    AwayTeamId INT NOT NULL,
    HomeTeamScore INT NOT NULL,
    AwayTeamScore INT NOT NULL
)

这不仅可以更直接地选择团队:

SELECT Name FROM Teams

但它也会构建一些真正的数据库完整性,因为您可以构建外键并且您不会使用简单的字符串值来指示键值。

于 2013-06-04T13:21:55.147 回答