修改查询以获取请求的值

时间:2013-08-02 08:30:06

标签: php mysql

请在此处使用此查询,以便从数据库中提取一些行。

$rs = mysql_query("SELECT u.*, SUM(c.ts) AS total_sum1, SUM(m.bv) AS total_sum 
FROM users u 
LEFT JOIN 
 (SELECT user_id ,SUM(points) AS ts FROM coupon GROUP BY user_id) c 
 ON   u.user_id like'%$search%'
LEFT JOIN 
 (SELECT user_id ,SUM(points) AS bv FROM matching GROUP BY user_id) m 
ON u.user_id=m.user_id 

GROUP BY u.user_id limit $offset,$rows");

我需要对其进行修改,以便只查询满足此条件的行:

u.user_id like '%$search%'

我应该把上述条件放在哪里? 我尝试添加AND运算符但它仍然不会给出一行,因为user_id彼此不同。

由于

2 个答案:

答案 0 :(得分:0)

您需要添加WHERE子句才能添加该条件:

$rs = mysql_query("SELECT u.*, SUM(c.ts) AS total_sum1, SUM(m.bv) AS total_sum 
FROM users u 
LEFT JOIN 
 (SELECT user_id ,SUM(points) AS ts FROM coupon GROUP BY user_id) c 
 ON   u.user_id like'%$search%'
LEFT JOIN 
 (SELECT user_id ,SUM(points) AS bv FROM matching GROUP BY user_id) m 
ON u.user_id=m.user_id 
WHERE u.user_id like '%$search%'
GROUP BY u.user_id limit $offset,$rows");

附注:

  • 不推荐使用mysql_*库,请考虑升级到现代API,例如PDO或MySQLi
  • 将带有绑定参数的Prepared Statements用于将变量连接到SQL中是首选。准备好的语句更安全,更易于使用,因为您不必担心转义。

答案 1 :(得分:0)

你可以尝试这个SQL。(我不知道PHP)

SELECT 
       u.*, 
       SUM(c.points) AS total_sum1, 
       SUM(m.points) AS total_sum 
FROM users u 

INNER JOIN coupon c  ON   u.user_id=m.user_id 
INNER JOIN matching  m  ON u.user_id=m.user_id 

WHERE u.user_id like '%$search%'
GROUP BY u.user_id limit $offset,$rows" ;