php - PHP MySQL 如何在 2 个表中选择 2 个特定值和 1 个公共值?
问题描述
我这里有两个表(只列出了重要的列):
table1: unique_code(INT), spediteur(VARCHAR also Names),
table2: unique_code(INT), versendet(timestamp)
我在这里有一个SELECT
但它不起作用,如果值是真的 - 这意味着:让我进入IF WHEN:
spediteur
值是Name
和versendet = 0000-00-00 00:00:00
和unique_code = $value
(unique_code/$value 在这两个表中必须相等)。
我试过这个:
$pdo = new PDO('myconnectionworks')
$stmt = pdo->prepare("SELECT * FROM table1 WHERE spediteur = 'Name' AND unique_code = $value
UNION ALL
SELECT * FROM table2 WHERE versendet = '0000-00-00 00:00:00' AND unique_code = $value");
$stmt->execute([$value]);
$result = $stmt->fetch();
if ($result){ "the unique_number exists in both tables and matches the id with the value spediteur 'Dachser' in table1 AND the value versendet ='0000-00-00 00:00:00' in table2" } else { "anything doesn´t work" }
这不起作用,因为它不允许我进入 if ,只是进入 else 部分。IF 是对成功操作的响应(保存其他值),else 是错误响应。
你对我有什么暗示吗?
用解决方案编辑。我使用了一个程序来帮助我弄清楚我可以使用什么语句。(dbForge Query Builder for MySQL) 好的,这是声明:
$stmt = $pdo->prepare("SELECT
table1.spediteur,
table2.versendet,
table2.unique_code,
table1.unique_code
FROM table1
INNER JOIN table2
ON table1.unique_code = table2.unique_code
WHERE table1.unique_code = $scanned_number
AND table2.unique_code = $scanned_number
GROUP BY table1.spediteur,
table2.versendet,
table2.unique_code,
table1.unique_code
HAVING table1.spediteur = 'Dachser'
AND table2.versendet = '0000-00-00 00:00:00'
");
$stmt->execute([$scanned_number]);
$result = $stmt->fetch();
if ($result) {
?> the scanned number matches the given parameter
<?php
$sql = "UPDATE table2 SET versendet = date('Y-m-d H:i:s') WHERE unique_code = $scanned_number";
$stmt = $pdo->prepare($sql);
$stmt->execute();
} else {
?> the scanned number don´t matches
<?php
}?>
我很欣慰,这个工具节省了我的时间。作为学习经验,我现在可以查看该声明以了解其工作原理。惊人的!
如果有人有其他解决方案,请告诉我。谢谢!