我正在尝试通过子查询(qcat)表从问题顺序中获取记录。我的代码是
"SELECT * FROM question
where survey_name='$_SESSION[ssn_sname]' AND
qcategory IN
( SELECT qcategory FROM qcat
WHERE client_name='$_SESSION[ssn_sname]'
GROUP BY qcategory
ORDER BY p_order
) AND
status='1' AND
survey_name LIKE'%$sname%
LIMIT $start, $limit";
但它没有按顺序得到结果。
如何通过qcat表获取行顺序?
答案 0 :(得分:0)
GROUP BY
子句 - 这用于聚合函数ORDER BY
- 让mysql为in
位进行操作ORDER BY
。即最后所以SQL应该是
"SELECT * FROM question
where survey_name='$_SESSION[ssn_sname]' AND
qcategory IN
( SELECT qcategory FROM qcat
WHERE client_name='$_SESSION[ssn_sname]'
) AND
status='1' AND
survey_name LIKE'%$sname%
ORDER BY p_order
LIMIT $start, $limit";
我也认为您可以首先避免子查询。但这需要对表格进行一些思考和更多的了解。
BTW - 注意SQL注入的可能性
答案 1 :(得分:-1)
您需要加入qcat
表,才能对该表中的其他列进行排序。试试这个:
$query = "
SELECT q.id question_id, q.*, c.*
FROM question q
INNER JOIN qcat c ON c.category = q.category
WHERE q.survey_name='$_SESSION[ssn_sname]'
AND c.client_name = '$_SESSION[ssn_sname]'
AND q.status='1'
AND q.survey_name like '%$sname%'
GROUP BY q.id
ORDER BY c.p_order
LIMIT $start, $limit";
注意:您的查询容易受到SQL Injection的攻击!