mixed_menu
SELECT mixed.unique_id,
MENU_LABEL
case
when (--something...)
FROM mixed_menu mixed
ORDER BY mixed.position ASC
问题:我想编写一个mysql查询,可以检索具有以下条件的unique_id,MENU_LABEL。
CASE1:
如果type ==' db_category'然后从数据库中检索标签( 1.db_category ),其中id = unique_id
案例2:
如果输入=='类别'然后从php数组中检索数组值( 2.PHP数组),其中数组键= unique_id
1。 db_category
2。 PHP数组
$category_array = array('car' => 'All Cars',
'jeep' => 'All Jeeps'
);
答案 0 :(得分:3)
如果使用php数组创建一个新表,会更容易。
但是使用您当前的结构,您可以创建一个像这样的临时/假表
SELECT * FROM (
SELECT 'car' as `id`, 'All Cars' as `label`
UNION
SELECT 'jeep' as `id`, 'All Jeeps' as `label`
) php
因此,您可以使用像
这样的查询SELECT mm.unique_id,
CASE
WHEN mm.type = 'db_category' THEN dbc.label
WHEN mm.type = 'category' THEN php.label
END as menu_label
FROM mixed_menu mm
LEFT JOIN db_category dbc ON mm.unique_id = dbc.id
LEFT JOIN (
/*Create fake table*/
SELECT 'car' as `id`, 'All Cars' as `label`
UNION
SELECT 'jeep' as `id`, 'All Jeeps' as `label`
) php ON mm.unique_id = php.id
ORDER BY mm.position ASC
这是一个SQLFiddle示例 - http://sqlfiddle.com/#!2/5630cc/5
然后你需要使用php数组构建那个假表。
修改强>
由于您的mixed_menu
和db_category
表格为COLLATION latin1_swedish_ci
,并且使用SELECT UNION
默认为COLLATION utf8_general_ci
,您需要在{{1}中声明此内容}}
SELECT UNION
现在查询将是
SELECT * FROM (
SELECT 'car' COLLATE latin1_swedish_ci as `id`, 'All Cars' COLLATE latin1_swedish_ci as `label`
UNION
SELECT 'jeep' COLLATE latin1_swedish_ci as `id`, 'All Jeeps' COLLATE latin1_swedish_ci as `label`
) php