Php 使用别名连接查询
我有一个查询来搜索三个东西,一个关键字,一个类别和一个地区(它的空缺)。除了区域之外,其他一切都正常工作,因为我从数据库中获得了一个别名为的列 我现在的代码:Php 使用别名连接查询,php,mysql,sql,database,Php,Mysql,Sql,Database,我有一个查询来搜索三个东西,一个关键字,一个类别和一个地区(它的空缺)。除了区域之外,其他一切都正常工作,因为我从数据库中获得了一个别名为的列 我现在的代码: $functie = $_POST['functie']; $branche = $_POST['branche']; $regio = $_POST['regio']; $search = " SELECT cnt.title as content_title, cnt.alias as content_alias, cnt.imag
$functie = $_POST['functie'];
$branche = $_POST['branche'];
$regio = $_POST['regio'];
$search = "
SELECT cnt.title as content_title, cnt.alias as content_alias, cnt.images, cnt.introtext, cnt.catid, cat.title as cat_title, cat.alias as cat_alias,
MAX(case when f.field_id = 2 then f.value end) as regio
FROM snm_content cnt
LEFT JOIN snm_categories cat
ON cat.id = cnt.catid
LEFT JOIN snm_fields_values f
ON cnt.id = f.item_id
";
// Collect all the where conditions in an array
$whr = array();
// check if $functie has some value in input filter
if (!empty($functie)) {
$whr[] = "cnt.title LIKE '%" . $functie . "%'";
}
if (!empty($regio)) {
$whr[] = "f.value LIKE '%" . $regio . "%'";
}
// check if $branche has some value in input filter
if (!empty($branche)) {
$whr[] = "cat.title LIKE '%" . $branche . "%'";
}
$where_sql = '';
// Prepare where part of the SQL
if (!empty($whr)) {
$where_sql = ' WHERE ' . implode(' OR ', $whr);
}
// Append to the original sql
$search .= $where_sql;
$searchcon = $conn->query($search);
但上述代码不适用于该地区
但是,这是endresult查询,我得到的结果如下:
SELECT cnt.title as content_title, cnt.alias as content_alias, cnt.images, cnt.introtext, cnt.catid, cat.title as cat_title, cat.alias as cat_alias,
MAX(case when f.field_id = 2 then f.value end) as regio
FROM snm_content cnt
LEFT JOIN snm_categories cat
ON cat.id = cnt.catid
LEFT JOIN snm_fields_values f
ON cnt.id = f.item_id
WHERE cnt.title LIKE '%vrachtwagen%'
regio
是我想要显示结果的地方
但是
WHERE regio像“%”“%$regio.”";代码>不起作用,它显示未知列regio
,因为它是一个别名。如何仅显示所发布区域的所有结果?例如上图,当Where
子句中的Select
子句中的Where
子句中不能使用带别名的计算表达式时,仅显示该行。请记住,Select
是在Where
之后求值的,因此表达式求值是在之后进行的
您必须在Where
子句中再次指定完整表达式
// check if $regio has some value in input filter
if (!empty($regio)) {
$whr[] = "MAX(case when f.field_id = 2 then f.value end) LIKE '%" . $regio . "%'";
}
查看您的代码,似乎您正在尝试将聚合结果max(…)过滤为regio
对于筛选聚合结果,您应该使用
HAVING regio like concat('%', $your_value, '%')
不管怎样,您在sql中使用的是php var,您的代码存在SQLInjection的风险。。您应该查看您的db驱动程序,了解准备好的语句和绑定参数
您还在“无分组依据的选择”中使用“未聚合”列。。这在sql中已被弃用,不允许在不可预测和最新版本的mysql中使用列的结果 我得到:运行查询[组函数的无效使用]时出错。
@twan为什么使用Max()
没有分组依据的函数
?您使用的是哪个版本的mysql db???@scaisEdge mysql PHPMYADMINWIC版本的db不是哪个ide。@twan请进一步阐述确定区域的逻辑
;也许有不同的方法。