复杂的MySQL组

时间:2013-06-04 13:15:38

标签: php mysql

我有一张桌子,其中包含两队之间足球比赛的结果。首先,我想要一个团队的下拉菜单。这应该只是SELECT * FROM table GROUP BY Team_A

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

4 个答案:

答案 0 :(得分:3)

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

select TeamA from table union
select TeamB from table

答案 1 :(得分: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;

答案 2 :(得分: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

答案 3 :(得分: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

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