我有两张桌子:球员和名片
在每个cards2行中,至少有一个玩家id(pid、pid2、pid3、pid4)。如果有多个玩家id(pid不是0),我将尝试使用select语句来获取所有fname和lname。总是有一个pid,但不总是一个pid2、pid3等等。这有意义吗?
这些是结构。
球员桌

CREATE TABLE IF NOT EXISTS `players` (
  `player_id` mediumint(10) NOT NULL AUTO_INCREMENT,
  `sport_id` tinyint(4) NOT NULL,
  `fname` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `lname` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `hof` tinyint(4) NOT NULL,
  PRIMARY KEY (`player_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=421 ;

卡片2表
CREATE TABLE IF NOT EXISTS `cards2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pid` mediumint(10) NOT NULL,
  `pid2` mediumint(10) NOT NULL,
  `pid3` mediumint(10) NOT NULL,
  `pid4` mediumint(10) NOT NULL,
  `num` smallint(4) NOT NULL DEFAULT '0',
  `year` year(4) NOT NULL DEFAULT '0000',
  `notes` text,
  `new_manuf` varchar(50) NOT NULL,
  `sportid` tinyint(4) NOT NULL DEFAULT '0',
  `fname` varchar(25) NOT NULL,
  `lname` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=572 ;

提前谢谢!

最佳答案

你可以这样做:

SELECT
    id,
    P1.fname AS fname1,
    P1.lname AS lname1,
    P2.fname AS fname2,
    P2.lname AS lname2,
    P3.fname AS fname3,
    P3.lname AS lname3,
    P4.fname AS fname4,
    P4.lname AS lname4
FROM cards2
LEFT JOIN players P1 ON pid = P1.player_id
LEFT JOIN players P2 ON pid2 = P2.player_id
LEFT JOIN players P3 ON pid3 = P3.player_id
LEFT JOIN players P4 ON pid4 = P4.player_id

不过,你可能想考虑一下normalize your database是否是个好主意。为四个玩家设置四个栏似乎是个坏主意。如果你以后想允许6个玩家怎么办?

关于sql - 帮助SELECT语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1995652/

10-11 20:41