如何在Kohana Framework中进行UNION ALL,查询

时间:2011-10-16 18:23:22

标签: php kohana

我怎么写这个:

SELECT
'Name' AS Type,
id AS Restaurant_ID,
NULL AS Item_ID,
Name,
Address,
NULL AS M_Id
FROM restaurants
WHERE Name LIKE '%forår%'
UNION ALL
SELECT
'Address' AS Type,
id AS Restaurant_ID,
NULL AS Item_ID,
Name,
Address,
NULL AS M_Id
FROM restaurants
WHERE Address LIKE '%forår%'
UNION ALL
SELECT
'Item' AS Type,
NULL AS Restaurant_ID,
id AS Item_ID,
Name,
NULL AS Address,
M_Id
FROM menu_items
WHERE name LIKE '%forår%'
查询构建器中的

我发现了这个:

How do I build a UNION query with ORDER BY and GROUP BY in Kohana's query builder?

还有3个查询:

        $query1 = 
        DB::select(
        array('name', 'Type'), 
        array('id', 'Restaurant_ID'), 
        array('NULL', 'Item_ID'), 'Name', 'Address', array('NULL', 'M_Id'))
        ->from('restaurants')
        ->where('Name', 'LIKE', '%forår%');

        $query2 =
        DB::select(
        array('Address', 'Type'),
        array('NULL', 'Item_ID'),
        Name,
        Address,
        array('NULL', 'M_Id'))
        ->from('restaurants')
        ->where('Address', 'LIKE', '%forår%');

        $query3 = 
        DB::select(
        array('Item', 'Type'),
        array('NULL', 'Restaurant_ID'),
        array('id', 'Item_ID'),
        Name,
        array('NULL', 'Address'),
        M_Id)
        ->from('menu_items')
        ->where('name', 'LIKE', '%forår%');

但现在我不知道应该如何以及在哪里应用union()

2 个答案:

答案 0 :(得分:4)

我没有检查你的代码,但试试这个:

$query1 = 
        DB::select(
            array('name', 'Type'), 
            array('id', 'Restaurant_ID'), 
            array('NULL', 'Item_ID'), 
            'Name', 
            'Address', 
            array('NULL', 'M_Id')
        )
        ->from('restaurants')
        ->where('Name', 'LIKE', '%forår%');

$query2 =
        DB::select(
            array('Address', 'Type'),
            array('NULL', 'Item_ID'),
            Name,
            Address,
            array('NULL', 'M_Id')
        )
        ->union($query1)
        ->from('restaurants')
        ->where('Address', 'LIKE', '%forår%');

$query3 = 
        DB::select(
            array('Item', 'Type'),
            array('NULL', 'Restaurant_ID'),
            array('id', 'Item_ID'),
            Name,
            array('NULL', 'Address'),
            M_Id
        )
        ->union($query2)
        ->from('menu_items')
        ->where('name', 'LIKE', '%forår%')
        ->execute();

答案 1 :(得分:1)

<?php

$query = DB::query(Database::SELECT, "SELECT
'Name' AS Type,
id AS Restaurant_ID,
NULL AS Item_ID,
Name,
Address,
NULL AS M_Id
FROM restaurants
WHERE Name LIKE '%:search%'
UNION ALL
SELECT
'Address' AS Type,
id AS Restaurant_ID,
NULL AS Item_ID,
Name,
Address,
NULL AS M_Id
FROM restaurants
WHERE Address LIKE '%:search%'
UNION ALL
SELECT
'Item' AS Type,
NULL AS Restaurant_ID,
id AS Item_ID,
Name,
NULL AS Address,
M_Id
FROM menu_items
WHERE name LIKE '%:search%'");

$query->param(':search', $_GET['search']);

$query->execute();