我想从单个查询中的两个表中获取或操作数据。有可能吗?
例:
SELECT * FROM t1 WHERE id = (SELECT id FROM t2 where column > 3 );
如果是这样,我是否也可以对两个表进行绑定。
答案 0 :(得分:2)
使用两个表显示参数的PDO绑定,为20岁或以下的人返回数据。
create table person
( id int auto_increment primary key,
fullname varchar(100) not null,
age int not null
);
create table transactions
( id int auto_increment primary key,
personId int not null,
transType varchar(10) not null,
amount decimal(12,2) not null,
foreign key fk_trans_per (personId) references person(id)
);
insert person(fullname,age) values
('Kim Billings',10),('Jason Cartwright',14),('xxx',1),('Older gent',40);
truncate table transactions;
insert transactions(personId,transType,amount) values
(1,'deposit',100),(1,'withd',11),(1,'withd',12),(1,'deposit',120),
(2,'deposit',10),(2,'deposit',20),(2,'xyz',12),(2,'deposit',30),
(4,'deposit',10);
<?php
// turn on error reporting, or wonder why nothing is happening at times
//mysqli_report(MYSQLI_REPORT_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set("display_errors", 1); // Begin Vault
// credentials from a secure Vault, not hard-coded
$servername="hostname";
$dbname="dbname";
$username="dbuser";
$password="password";
// End Vault
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$maxAge=20;
$theType="deposit";
// return deposit totals for people 20 or younger
$sql="select p.id,sum(t.amount) as total from person p join transactions t on t.personId=p.id";
$sql.=" where p.age <= :maxAge and t.transType=:ttype";
$sql.=" group by p.id";
$stmt = $db->prepare($sql);
$stmt->bindParam(':maxAge', $maxAge, PDO::PARAM_INT);
$stmt->bindParam(':ttype', $theType, PDO::PARAM_STR, 10);
$stmt->execute();
// http://php.net/manual/en/pdostatement.fetch.php
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "id=".$row['id'] .", total=".$row['total']."<br>";
}
// .. other cleanup as necessary
} catch (PDOException $e) {
echo 'PDO error: ' . $e->getMessage();
exit();
}
?>
id=1, total=220.00
id=2, total=60.00
答案 1 :(得分:0)
您可以使用PDO::query - 执行自定义的SQL语句
<?php
$servername="hostname";
$dbname="dbname";
$username="dbuser";
$password="password";
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$row = $db->query("SELECT * FROM t1 WHERE id = (SELECT id FROM t2 where column > 3 )")->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
var_dump($row);
echo "</pre>";