0

我试图根据一些基本的 where 子句从表中获取行,现在我想在最后包含一个“AND EXISTS”子句。我的代码如下:

$stmt = $mysqli->prepare("SELECT object_id FROM ".
          $db_table_prefix."user_events
          WHERE LPAD(start_timestamp,15,'0') < LPAD(?,15,'0')
          AND event_id = ?
          AND EXISTS ( 
            SELECT * FROM ".$db_table_prefix."user_events
              WHERE LPAD(start_timestamp,15,'0') > LPAD(?,15,'0')
              AND event_id = ? )
        ");

我遇到的问题是我不知道如何从 AND EXISTS 子查询中的主查询中指定列值。

我正在寻找一种将这一位添加到子查询中的方法:

AND object_id = **object_id from main query**

任何帮助表示赞赏

4

3 回答 3

1

而不是EXISTS,您可能会发现这里的自联接语法更清晰,我无法从您的代码中准确推断出您想要什么,而是要获取object_id在特定时间之前开始的事件,并且稍后也会再次开始:

SELECT  ue1.object_id 
FROM    user_events ue1 join user_events ue2
WHERE   ue1.event_id = ue2.event_id AND
        ue1.object_id = ue2.object_id AND
        ue1.event_id = ? AND 
        LPAD(ue1.start_timestamp, 15, '0') < LPAD(ue2.start_timestamp, 15, '0') AND 
        LPAD(ue1.start_timestamp, 15, '0') < LPAD(?, 15, '0')
于 2013-10-08T09:54:02.280 回答
1

此外,为子查询的表添加了别名以避免混淆

$stmt = $mysqli->prepare("SELECT object_id FROM ".
      $db_table_prefix."user_events
      WHERE LPAD(start_timestamp,15,'0') < LPAD(?,15,'0')
      AND event_id = ?
      AND EXISTS ( 
        SELECT * FROM ".$db_table_prefix."user_events AS u
          WHERE LPAD(u.start_timestamp,15,'0') > LPAD(?,15,'0')
          AND u.object_id = " .$db_table_prefix.".object_id
          AND u.event_id = ? )
    ");
于 2013-10-08T09:51:25.607 回答
0

和 object_id in (select object_id from ...

于 2013-10-08T09:45:20.087 回答