【发布时间】:2018-12-07 00:21:00
【问题描述】:
我有表table_tudo 和followItem,在表table_tudo 上我有1 列称为tipo,可以有三个值之一tipoEp, tipoOv and tipoFm,在这两个表上我想INNER JOIN dateMD 和 itemName 列之后,我想在屏幕上仅打印与此条件匹配的项目 table_tudo.dateMD > followItem.dateMD AND followItem.user_id = :user_id AND table_tudo.tipo = :tipoEp OR table_tudo.tipo = :tipoFm OR table_tudo.tipo = :tipoOv。
在我的查询结束时,我使用了GROUP BY,因为它显示了重复的行。
我无法使用 AND 到 INNER JOIN 2 个表中的 2 个列,然后我尝试使用 OR 并且它有效,但现在我遇到了另一个问题,条件 table_tudo.dateMD > followItem.dateMD 不起作用对于table_tudo.tipo = :tipoFm OR table_tudo.tipo = :tipoOv,这些tipo 的行都打印在屏幕上,该条件仅适用于table_tudo.tipo = :tipoEp。
我的查询有什么问题? PS:bindParam里面的变量是全局变量。
$MTEpPRP = $conn->prepare("SELECT * FROM `table_tudo` INNER JOIN `followItem` ON `table_tudo`.`itemName` = `followItem`.`itemName` OR `table_tudo`.`dateMD` = `followItem`.`dateMD` WHERE `table_tudo`.`dateMD` > `followItem`.`dateMD` AND `followItem`.`user_id` = :user_id AND `table_tudo`.`tipo` = :tipoEp OR `table_tudo`.`tipo` = :tipoFm OR `table_tudo`.`tipo` = :tipoOv GROUP BY `table_tudo`.`id`");
$MTEpPRP->bindParam(':tipoEp', $tipoEp, PDO::PARAM_STR);
$MTEpPRP->bindParam(':tipoFm', $tipoFm, PDO::PARAM_STR);
$MTEpPRP->bindParam(':tipoOv', $tipoOv, PDO::PARAM_STR);
$MTEpPRP->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$MTEpPRP->execute();
我做了一些测试,我也意识到table_tudo.tipo = :tipoFm OR table_tudo.tipo = :tipoOv 中的行只有在我的查询table_tudo.tipo = :tipoEp 中有这一行时才会在屏幕上打印出来。
我相信问题出在INNER JOIN 上,因为我在下面测试了这些查询并且它有效:
$MTEpPRP = $conn->prepare("SELECT * FROM `table_tudo` WHERE `table_tudo`.`tipo` = :tipoOv");
$MTEpPRP->bindParam(':tipoOv', $tipoOv, PDO::PARAM_STR);
$MTEpPRP->execute();
$MTEpPRP = $conn->prepare("SELECT * FROM `table_tudo` WHERE `table_tudo`.`tipo` = :tipoFm");
$MTEpPRP->bindParam(':tipoFm', $tipoFm, PDO::PARAM_STR);
$MTEpPRP->execute();
$MTEpPRP = $conn->prepare("SELECT * FROM `table_tudo` WHERE `table_tudo`.`tipo` = :tipoFm OR `table_tudo`.`tipo` = :tipoOv");
$MTEpPRP->bindParam(':tipoFm', $tipoFm, PDO::PARAM_STR);
$MTEpPRP->bindParam(':tipoFm', $tipoOv, PDO::PARAM_STR);
$MTEpPRP->execute();
【问题讨论】:
-
i tested this query哪个查询?有很多 -
这不是一个答案,但在加入表格时声明别名对缩短代码有很大帮助。
-
Natalie,请告诉我们这两个表的主键。或者您可以发送表格中的示例数据。这只是为了了解表的行为
-
没有数据和参数值,这个问题是无法回答的。
-
@AnuraAdhikari 表
table_tudo上的主键是id,表followItem上的主键是num,两者都带有AUTO_INCREMENT。 “发送表格中的示例数据”我不知道是什么意思...
标签: mysql sql database join inner-join