如何从两个表中检索数据

时间:2016-04-27 15:48:39

标签: mysql

这是我的两个表的数据库结构

CREATE TABLE `futstkrprices` (
  `name` varchar(50) DEFAULT NULL,
  `expiry_date` varchar(25) DEFAULT NULL,
  `contract_type` varchar(50) DEFAULT NULL,
  `close_price` decimal(15,2) DEFAULT NULL
  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `historical_data` (
  `symbol_name` varchar(70) DEFAULT NULL,
  `open_val` decimal(15,2) DEFAULT NULL,
  `high_val` decimal(15,2) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO futstkrprices (name,expiry_date,contract_type,close_price)
values ('ABIRLANUVO' ,'26-MAY-2016','FUTSTK',870.65);
INSERT INTO futstkrprices (name,expiry_date,contract_type,close_price)
values ('ABIRLANUVO' ,'28-APR-2016','FUTSTK',866.40);
INSERT INTO futstkrprices (name,expiry_date,contract_type,close_price)
values ('ABIRLANUVO' ,'30-JUN-2016','FUTSTK',875.95);


INSERT INTO historical_data (symbol_name,open_val,high_val) values ('ABIRLANUVO',872.00,878.25)

以下是小提琴样本

http://sqlfiddle.com/#!9/1d4f20

您能告诉我如何从两个表中检索数据 我已经尝试过了,但它不起作用

select futstkrprices.name ,  futstkrprices.expiry_date , futstkrprices.close_price , historical_data.symbol_name ,
historical_data.open_val , historical_data.high_val from  futstkrprices  LEFT JOIN futstkrprices 
ON futstkrprices.name=historical_data.symbol_name;

我期待的期望输出是

name       expiry_date close_price symbol_name open_val high_val
ABIRLANUVO 26-MAY-2016      870.65 ABIRLANUVO       872   878.25
ABIRLANUVO 28-APR-2016      866.4  ABIRLANUVO       872   878.25
ABIRLANUVO 30-JUN-2016      875.95 ABIRLANUVO       872   878.25

1 个答案:

答案 0 :(得分:1)

你在同一张桌子from futstkrprices LEFT JOIN futstkrprices

中重复了两次

试试这个

  select 
   futstkrprices.name ,  
   futstkrprices.expiry_date ,   
   futstkrprices.close_price , 
   historical_data.symbol_name ,
   historical_data.open_val ,
   historical_data.high_val 
 from  futstkrprices  
 LEFT JOIN historical_data
   ON futstkrprices.name=historical_data.symbol_name;