将复杂的SQL语句转换为PDO

时间:2012-07-19 22:26:59

标签: php mysql sql pdo

我有以下sql语句,这是完美的,因为我将所有内容转移到PDO,我有最糟糕的时间尝试转换这个复杂的语句。这是在下面工作:

$sql_res=mysql_query("SELECT a.first_name, a.last_name, a.uid, a.hometown, 
IF(b.friend_two IS NULL, 0, 1) AS isFriend FROM users a LEFT JOIN friends 
b ON a.uid = b.friend_two AND b.friend_one = $uid WHERE  
CONCAT(a.first_name, ' ', a.last_name) LIKE '%$q%' AND a.uid <> $uid 
ORDER BY isFriend DESC");

我一直在尝试转换几个小时,这是我从另一个S.O示例中得到的全部(它甚至不接近工作)

任何帮助都非常感谢。哦,$ q也是来自用户的POST变量,因此在我的情况下,PDO是必须的。

更新代码(第2次):

$sql = "select a.first_name, a.last_name, a.uid, a.hometown, 
IF(b.friend_two IS NULL, 0, 1) AS isFriend FROM users a LEFT JOIN 
friends b ON a.uid = b.friend_two AND b.friend_one = :friend_one 
where ( first_name like concat('%', :fname, '%') or last_name like 
concat('%', :lname, '%') ) and a.uid <> :uid ORDER BY isFriend DESC"; 
$stmt= $db->prepare($sql); $stmt->bindValue(':fname', "%$q%", PDO::PARAM_STR); 
$stmt->bindValue(':lname', "%$q%", PDO::PARAM_STR); 
$stmt->execute(array(':friend_one' => $uid,':uid' => $uid));

这没有任何错误,但无法产生与原始sql语句相同的结果。

1 个答案:

答案 0 :(得分:0)

删除了额外的from并将()放在您的名称过滤器周围,作为
A OR B AND C = A OR (B AND C),我猜你想要(A OR) B AND C

select
  a.first_name,
  a.last_name,
  a.uid,
  a.hometown,
  IF(b.friend_two IS NULL, 0, 1) AS isFriend 
FROM users a 
LEFT JOIN friends b
  ON a.uid = b.friend_two AND b.friend_one = :uid
where 
  (
    first_name like concat('%', :fname, '%') or 
    last_name  like concat('%', :lname, '%') 
  ) and
  a.uid <> :uid 
ORDER BY
  isFriend DESC