尝试使用存储过程访问三个表但只接收一行

时间:2013-06-20 17:18:36

标签: mysql phpmyadmin

到目前为止,我尝试了许多使用存储过程访问三个表上数据的不同方法。首先,我尝试了一个简单的选择语句:

create procedure reportCodes () begin
SELECT Numbers.serial_numb, numOwner.lName, numOwner.fName, numOwner.email,
 location.long, location.lat, Numbers.dateValidated
FROM Numbers, Owner, location
WHERE Numbers.used = true AND Numbers.id=numOwner.Numbers_id AND     
 Numbers.id=location.Numbers_id; 
end$$

(更改名称以保护有罪者)

在phpmyadmin中运行存储过程会导致记录的第一个实例(测试数据库中两个“true”中的一个)。正好跑:

SELECT Numbers.serial_numb, numOwner.lName, numOwner.fName, numOwner.email,  
 location.long, location.lat, Numbers.dateValidated
FROM Numbers, Owner, location
WHERE Numbers.used = true AND Numbers.id=numOwner.Numbers_id AND 
Numbers.id=location.Numbers_id;
phpmyadmin SQL选项卡中的

返回两个记录。然后我尝试了临时表:

create procedure reportCodes () begin
CREATE TEMPORARY TABLE used_numbers AS (
SELECT Numbers.serial_numb, numOwner.lName, numOwner.fName, numOwner.email,
 location.long, location.lat, Numbers.dateValidated
FROM Numbers, Owner, location
WHERE Numbers.used = true AND Numbers.id=numOwner.Numbers_id AND 
 Numbers.id=location.Numbers_id);

SELECT * FROM used_numbers; end$$

返回2条记录中的1条作为过程,但两条记录都在控制台中。最后我尝试将我的表格改为连接:

CREATE PROCEDURE reportCodes()
begin
create temporary table used_numbers AS (
SELECT Numbers.serial_numb, numOwner.lName, numOwner.fName, numOwner.email,
 location.long, location.lat, Numbers.dateValidated
FROM Numbers JOIN numOwner
ON Numbers.id=numOwner.Numbers_id 
JOIN location ON
 numOwner.Numbers_id=location.Numbers_id
WHERE Numbers.used = true
);

SELECT * FROM used_numbers; end$$

与上述结果相同。我不知道为什么只运行SQL会显示两个测试记录,但运行具有完全相同代码的过程只产生一个。 感谢

1 个答案:

答案 0 :(得分:0)

在你的查询中,numOwners不是被选中的有效表,所以有些错误。您是否尝试在phpMyAdmin的Query窗口中运行SQL以确保EXACT相同的查询返回2行?

我认为“Owner”表应该是“numOwner”,所以我在下面重写了存储过程调用。此外,我不确定您在Numbers.used中存储的值是什么类型以评估为“TRUE”。我会假设你正在使用TINYINT(1),所以我也改变了它。我希望这会有所帮助。

DELIMITER $$

USE `db`$$

DROP PROCEDURE IF EXISTS `reportCodes`$$

CREATE PROCEDURE `reportCodes`()
BEGIN
  SELECT 
    n.serial_numb, 
    o.lName, 
    o.fName, 
    o.email,  
    l.long, 
    l.lat, 
    n.dateValidated
  FROM Numbers n
  INNER JOIN numOwner o ON n.id=o.Numbers_id 
  INNER JOIN location l ON n.id=l.Numbers_id; 
  WHERE n.used = 1
END$$

DELIMITER ;