【发布时间】:2017-04-25 07:51:14
【问题描述】:
以下查询显示汤列表,以及每种汤的成分列表。
//Query only for demonstration
SELECT a.id_soup, a.soup,
GROUP_CONCAT(DISTINCT b.id_vegetables) AS vegetables_id,
GROUP_CONCAT(DISTINCT b.vegetables) AS vegetables_list
FROM soups a
LEFT JOIN ingredients ing ON a.soup = ing.soup_id
LEFT JOIN vegetables b ON b.id_vegetables = ing.list_vegetables
GROUP BY a.id_soup
我想过滤记录,以便只显示汤中含有某种成分(例如土豆)的记录。比如:
SELECT a.id_soup, a.soup,
GROUP_CONCAT(DISTINCT b.id_vegetables) AS vegetables_id,
GROUP_CONCAT(DISTINCT b.vegetables) AS vegetables_list
FROM soups a
LEFT JOIN ingredients ing ON a.soup = ing.soup_id
LEFT JOIN vegetables b ON b.id_vegetables = ing.list_vegetables
AND ing.list_vegetables LIKE "potatoes"
GROUP BY a.id_soup
这些查询过滤了记录,但是配料列表不再显示汤的所有配料,只显示配料土豆。
正确执行此操作的最佳方法是什么?
已编辑:
有多个条件 - PHP 和 SQL:
$typesQuery = "";
$bind=array();
sqlQuery = "SELECT a.id_soup, a.soup, a.restaurant,
GROUP_CONCAT(DISTINCT b.id_vegetables) AS vegetables_id,
GROUP_CONCAT(DISTINCT b.vegetables) AS vegetables_list
FROM soups a
LEFT JOIN ingredients ing ON a.soup = ing.soup_id
LEFT JOIN vegetables b ON b.id_vegetables = ing.list_vegetables ";
if($restaurant) {
$sqlQuery .= " AND a.restaurant LIKE ? ";
$typesQuery .= "s" ;
$bind[] = $restaurant;
}
if($vegetables) {
$sqlQuery .= " AND ... ";
$typesQuery .= "s" ;
$bind[] = $vegetables;
}
//EDITED:
$vegetables = 'potatoes';
if($vegetables) {
$sqlQuery .= " HAVING SUM(CASE WHEN b.vegetables IN (?) THEN 1 ELSE 0 END) = 1 ";
$typesQuery .= "s" ;
$bind[] = $vegetables;
}
$sqlQuery .= " GROUP BY a.id_soup LIMIT ?,? ";
if ($statementQuery = $conexion->prepare($sqlQuery)){
$typesTotal = $typesQuery;
$bindTotal = array_merge(array(), $bind);
$typesQuery .= "ii";
$bind[] = $start;
$bind[] = $limit;
array_unshift($bind, $typesQuery);
call_user_func_array( array($statementQuery, 'bind_param'), makeValuesReferenced($bind) );
}else{
$error = $conexion->error;
$success = false;
break;
}
...
【问题讨论】: