ALL,
考虑以下数据库架构:
CREATE TABLE players(playerid integer primary key, playertype integer, ....);
CREATE TABLE scoretype1(scoreid integer primary key, scorename varchar);
CREATE TABLE scoretype2(scoreid integer primary key, scorename varchar);
CREATE TABLE scoreforplayerstype1(playerid integer, scoreid integer, value double, foreign key(playerid) references players(playerid), foreign key(scoreid) references scoretype1(scoreid));
CREATE TAble scoreforplayerstype2(playerid integer, scoreid integer, value double, foreign key(playerid) references players(playerid), foreign key(scoreid) references scoretype2(scoreid));
现在出现问题:
是否可以在一个查询中获取所有玩家的得分值,或者我必须对类型1和类型2进行2次查询?我希望得到一个球员的得分名和得分值。
谢谢。
答案 0 :(得分:1)
SELECT P1.PLAYERID, S1.SCORENAME, J1.VALUE
FROM PLAYERS AS P1
INNER JOIN SCOREFORPLAYERSTYPE1 AS J1
ON J1.PLAYERID = P1.PLAYERID
INNER JOIN SCORETYPE1 AS S1
ON S1.SCOREID = J1.SCOREID
UNION ALL
SELECT P2.PLAYERID, S2.SCORENAME, J2.VALUE
FROM PLAYERS AS P2
INNER JOIN SCOREFORPLAYERSTYPE2 AS J2
ON J1.PLAYERID = P1.PLAYERID
INNER JOIN SCORETYPE2 AS S2
ON S1.SCOREID = J1.SCOREID
答案 1 :(得分:0)
SELECT p.playerid
,p.playertype
,IFNULL(sfp1.value, sfp2.value) AS value
,IFNULL(st1.scorename, st2.scorename) AS scorename
FROM players p
LEFT JOIN scoreforplayerstype1 sfp1 ON p.playerid = sfp1.playerid
LEFT JOIN scoreforplayerstype2 sfp2 ON p.playerid = sfp1.playerid
LEFT JOIN scoretype1 st1 ON sfp1.scoreid = st1.scoreid
LEFT JOIN scoretype2 st2 ON sfp2.scoreid = st2.scoreid
应该这样做,但正如评论所示,你应该重新考虑你的表结构。