从两个表mysql中选择多行

时间:2012-07-20 12:13:43

标签: mysql select

我试图从拖车表中选择多行: 第一个表是捐助者

       CREATE TABLE donor(
   donor_number INT NOT NULL AUTO_INCREMENT,
   d_name VARCHAR(30) NOT NULL,
   mobile_number INT NOT NULL,
   blood_group VARCHAR(20) NULL,
      dob DATE NOT NULL,
   gender ENUM('male','female') NOT NULL,
    govid INT(10) NOT NULL,
   PRIMARY KEY (donor_number  )

);

第二张表是blood_donation

    CREATE TABLE blood_donation(

   donor_number INT NOT NULL,
   date_of_donate DATE NOT NULL,
   blood_group VARCHAR(20) NULL,
   serial_number INT(10) NOT NULL,
   blood_component ENUM('wb','prcb') NOT NULL,
   PRIMARY KEY (donor_number , date_of_donate ),
   FOREIGN KEY (donor_number) REFERENCES donor(donor_number) 

   );

使用这个select语句:

        SELECT 
serial_number,
blood_group
FROM blood_donation
WHERE date_of_donate = '2012-07-18'
UNION ALL
SELECT 
blood_group
FROM donor
WHERE donor.donor_number=blood_donation.donor_number;

但是,我收到了错误

    SQL state 42S22: Unknown column 'blood_donation.donor_number' in 'where clause'
any idea????

3 个答案:

答案 0 :(得分:0)

UNION用于将多个结果集合并到一个结果集中 - 每个结果集必须具有相同的列集。

你需要的是一个JOIN,这是你在外键等上将多个表链接在一起的方式,就像这样:

SELECT 
  serial_number,
  blood_group
FROM blood_donation
INNER JOIN donor ON donor.donor_number=blood_donation.donor_number
WHERE date_of_donate = '2012-07-18'

答案 1 :(得分:0)

实际上你不应该使用UNION而是加入:)

您的查询将如下所示

SELECT 
  blood_donation.serial_number,
  donor.blood_group 
FROM
  blood_donation ,
  donor 
WHERE donor.donor_number = blood_donation.donor_number  AND date_of_donate = '2012-07-18' ;

答案 2 :(得分:0)

 SELECT 
dd.serial_number,
dd.blood_group
FROM blood_donation dd
inner join
donor d
on d.donor_number=dd.donor_number
WHERE dd.date_of_donate = '2012-07-18';

UNION并不是您需要的内容,请阅读有关JOINS的更多信息。另外,请根据需要更改列的选择别名。如果您不希望在表格上使用强制连接条件,则可以使用Left Join代替Inner Join