PHP - mysqli绑定参数中的相同值

时间:2015-10-15 22:36:37

标签: php mysqli sqlbindparameter

我可以优化此代码吗? mysqli_stmt_bind_param($statement, "iiiiiii", $user, $user, $user, $user, $user, $user, $user);

用于此请求:

$statement = mysqli_prepare($conn, "SELECT u_id, u_lastname, u_firstname, 
    (SELECT f_id from friend where (f_friend_one = u_id AND f_friend_two = ?) OR (f_friend_one = ? AND f_friend_two = u_id)),
    (SELECT f_type from friend where (f_friend_one = u_id AND f_friend_two = ?) OR (f_friend_one = ? AND f_friend_two = u_id))
FROM    user
WHERE   (( u_id = ( SELECT f_friend_one FROM friend WHERE f_friend_one = u_id AND f_friend_two = ? AND (f_type = 1 OR f_type = 4))) 
OR      ( u_id = ( SELECT f_friend_two FROM friend WHERE f_friend_one = ? AND f_friend_two = u_id AND (f_type = 1 OR f_type = 3))))
AND     u_id != ? ")
    or die(mysqli_error($conn));

1 个答案:

答案 0 :(得分:2)

我认为你可以简化它:

SELECT u_id, u_lastname, f_id, f_type
FROM user
JOIN friend
    ON (u_id = f_friend_one AND f_friend_two = ? AND f_type IN (1, 4))
        OR
       (u_id = f_friend_two AND f_friend_one = ? AND f_type IN (1, 3))
WHERE u_id != ?

最终可能不需要WHERE条款,因为有人无法向自己发送朋友请求。

OR可能会让MySQL难以优化,因此最好将其拆分为与UNION连接的两个子查询。

SELECT u_id, u_lastname, f_id, f_type
FROM user
JOIN friend ON u_id = f_friend_one
WHERE f_friend_two = ? AND f_type IN (1, 4))
    AND u_id != ?

UNION

SELECT u_id, u_lastname, f_id, f_type
FROM user
JOIN friend ON u_id = f_friend_two
WHERE f_friend_one = ? AND f_type IN (1, 3))
    AND u_id != ?