简体   繁体   中英

SQL multiple selecting from two tables and group

i have problem with select.

I managed to write a query that was doing something similar but I was able to pull data after only one I need to group as a team but with two names

I have a problem to write one question, I need to pick something about this style

team_id | player1       | player2       | position  | category
1       | John Newman   | Andy Roddick  | 1         | 1
2       | Roger Federer | Rafael Nadal  | 1         | 1

I have two tables/ one contains players and second contains attendance in team/

CREATE TABLE IF NOT EXISTS `atendance` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `player1` int(11) NOT NULL,
  `player2` int(11) NOT NULL,
  `position` int(11) NOT NULL,
  `category` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci AUTO_INCREMENT=22 ;



CREATE TABLE IF NOT EXISTS `players` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(12) COLLATE utf8_czech_ci NOT NULL,
  `surname` varchar(24) COLLATE utf8_czech_ci NOT NULL,
  `datum_n` date NOT NULL,
  `klub` varchar(60) COLLATE utf8_czech_ci NOT NULL,
  `tel` varchar(12) COLLATE utf8_czech_ci NOT NULL,
  `mail` varchar(32) COLLATE utf8_czech_ci NOT NULL,
  `cas` text COLLATE utf8_czech_ci NOT NULL,
  `foto` text COLLATE utf8_czech_ci NOT NULL,
  `pass` text COLLATE utf8_czech_ci NOT NULL,
  `is_active` tinyint(1) NOT NULL DEFAULT '0',
  `valid_from` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `valid_until` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `is_admin` tinyint(1) NOT NULL DEFAULT '0',
  `pohlavie` varchar(6) COLLATE utf8_czech_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci AUTO_INCREMENT=25 ;

As much as i understood, all the required data is in first table. You just need to fire,

SELECT ID, PLAYER1, PLAYER2, POSITION, CATEGORY FROM ATENDANCE

Please note, instead of CREATE commands provide the output result of that table, as you want SELECT statement to be built. It makes easier to understand.

I think you need to use JOIN particularly LEFT JOIN , like:

SELECT t.id, p1.name, p2.name, t.position, t.category
FROM atendance t
LEFT JOIN players p1
ON t.player1 = p1.id
LEFT JOIN players p2
ON t.player2 = p2.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM