如何在PHP中正确放置mysql查询?

时间:2011-05-20 03:39:33

标签: php mysql sql

我有mysql查询:

SET @row = 0; 

SELECT @row := @row + 1 AS Row, col1 
  FROM table1;

但如何正确放入$sql=",,,,,,";

我trid:

SET @row = 0; 
$sql = "SELECT @row := @row + 1 AS Row, col1 
          FROM table1";

但我认为它不起作用,然后尝试:

$sql = "SELECT @row := @row + 1 AS Row, col1 
          FROM table1,
               (SELECT @rownum = 0)";

没有错误,但我得到Row的结果为null 这是真正的查询:

SELECT @rownum:=@rownum+1 AS No, B.Serial_number,A.Symptom 
        FROM oqc_defect A
        JOIN (SELECT @rownum := 0) r
        LEFT JOIN inspection_report B
        ON A.Model = B.Model
        WHERE Appearance = 'NG' OR Packing = 'NG' OR Accesories = 'NG' OR Tuner = 'NG' OR General_operation = 'NG'
        GROUP BY A.Model

我得到的结果如下:

No  Serial_number   Symptom
1   106X0336    Remocon Wrong Part Number
6   106X0528    Trimplate have scratch
7   106V8024    IC breaket not lock to top chassis
8   106X5890    IC breaket not lock to top chassis
9   106X5866     IC breaket not lock to top chassis
10  106X0781    Finder crack at bottom side

1 个答案:

答案 0 :(得分:1)

使用:

$sql = "SELECT @rownum := @rownum + 1 AS Row, 
               t.col1 
          FROM table1 t
          JOIN (SELECT @rownum := 0) r ";

我纠正了什么:

  • 您需要:=来设置变量
  • 您声明的变量为@rownum,而不是您自己添加的@row

PHP的mysql_query不支持多个查询,因此使用SET的版本将不会像您发布的那样工作。我提供的解决方案不需要SET语句,因此可以在mysql_query中运行...