0

请我在这里有这个查询,我用它来从数据库中提取一些行。

$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 彼此不同。

谢谢

4

2 回答 2

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" ;
于 2013-08-02T09:15:09.430 回答
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
  • 使用带有绑定参数的预处理语句优于将变量连接到 SQL 中。Prepared Statements 更加安全且易于使用,因为您不必担心转义。
于 2013-08-02T08:33:39.730 回答