sql连接一个表中的两个字段

时间:2011-10-28 13:55:21

标签: mysql sql

我有两个人的预订表 - 我想将person_1作为一行返回,person_2作为新行返回,但是该人员的id与人员表相关

这是我得到的 - 但没有提取预订信息

 SELECT people.* FROM (
    (select booking.person_1 as id from booking)
    union ALL
    (select booking.person_2 as id from booking)
) as peopleids
join people on people.id = peopleids.id;

继承我的结构

CREATE TABLE IF NOT EXISTS `booking` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `slot` enum('morning_drive','afternoon_loop','return_drive') NOT NULL,
  `type` enum('911','vintage_911') NOT NULL,
  `car` int(11) NOT NULL,
  `person_1` int(11) DEFAULT NULL,
  `person_2` int(11) DEFAULT NULL,
  `dated` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;


CREATE TABLE IF NOT EXISTS `people` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `organisation` varchar(100) NOT NULL,
  `event_date` date NOT NULL,
  `wave` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

关于如何获得结果集的任何想法,如person.first_name,person.last_name,person.organisation,booking.dated,person.car,person.slot。我正在努力争取拥有两个领域并让他们将它们联系到一个列表中

对任何对此感兴趣并加入第3张表格的人进行更新

继续我的最后查询与php vars拉入我的某些日期和插槽并加入第三个表

    SELECT peopleids.id, 
       peopleids.car, 
       cars.nr, 
       p.first_name, 
       p.last_name, 
       p.organisation, 
       p.event_date, 
       p.wave 
FROM (SELECT booking.car, booking.person_1 as id FROM booking WHERE booking.dated = '".$date."' AND booking.`slot` =  '".$slot."' 
        union ALL SELECT booking.car, booking.person_2 as id FROM booking  WHERE booking.dated = '".$date."' AND booking.`slot` = '".$slot."' 
     ) as peopleids
LEFT JOIN people p ON p.id = peopleids.id  LEFT JOIN cars on cars.id = peopleids.car;

2 个答案:

答案 0 :(得分:1)

 SELECT 
       ag.id, 
       p.first_name, 
       p.last_name, 
       p.organisation, 
       p.event_date, 
       p.wave
 FROM (
      SELECT booking.person_1 as id, booking.Car as car FROM booking
      union ALL
      SELECT booking.person_2 as id, booking.Car as car FROM booking
     ) as ag
JOIN people p ON people.id = ag.id;
INNER | LEFT JOIN Cars c ON c.ID = ag.car

答案 1 :(得分:0)

    select people.first_name as firstname,
            people.last_name as lastname,
            people.organisation,
            booking.dated,
            booking.car,
            booking.slot from booking
left join people on booking.person_1 = people.id

OR

select people.first_name as firstname,
            people.last_name as lastname,
            people.organisation,
            booking.dated,
            booking.car,
            booking.slot
 from booking
left join people on booking.person_1 = people.id or booking.person_2 = people.id

检查......如果你仍然需要帮助会帮助你