如何在这个SQL查询中使用0-20之间的范围?

时间:2015-03-26 09:57:00

标签: mysql sql database drupal drupal-7

如何在此sql查询中使用0-20之间的范围?

  $sql = 'SELECT * FROM t1
          LEFT JOIN t2 ON t2.wid = t1.wid  
          UNION
          SELECT * FROM t1
          RIGHT JOIN t2 ON t2.wid = t1.wid
          limit 0, 20';
  $result = db_query($sql);//->fetchField();

2 个答案:

答案 0 :(得分:1)

将LIMIT传递给您的查询。并且你的限制每次都会变化,如

$sql = 'SELECT * FROM (SELECT * FROM t1
          LEFT JOIN t2 ON t2.wid = t1.wid  
          UNION
          SELECT * FROM t1
          RIGHT JOIN t2 ON t2.wid = t1.wid) AS A LIMIT'.$start.','.$end

答案 1 :(得分:0)

请请对您的查询进行sanatize,因为这很容易SQL注入。对于drupal应该是:

$result = db_query('SELECT * FROM (SELECT * FROM t1
      LEFT JOIN t2 ON t2.wid = t1.wid  
      UNION
      SELECT * FROM t1
      RIGHT JOIN t2 ON t2.wid = t1.wid) AS A LIMIT :min, :max',
      array('min' => $min, 'max' => $max));

有更好的Drupal方法可以写这个,但只要你把变量作为参数传递就可以了。