SQL:加入2个查询

时间:2014-08-12 21:53:50

标签: mysql sql

我正在为朋友的网站创建查询。他希望在他的所有内容(即(子)页面标题和内容)中搜索字符串。由于他的数据库设计,我不得不进行2次查询(1个用于页面标题/内容,1个用于子页面标题/内容),因为子页面需要一些额外的值(subpageID和pageID)。

有没有办法在1中加入这两个查询?它会使我的代码使用这些查询更容易:)

我对SQL的了解还不足以解决这个问题。

-- Query 1
SELECT
    active, deleted, ID, page_ASP, page_title_EN, page_text_EN
FROM
    sub_menu
WHERE 
    page_title_EN LIKE '%europe%'
    OR page_text_EN LIKE '%europe%'
    AND active = 1
    AND deleted = 0

-- Query 2
SELECT
    sub.active AS 'active', sub.deleted AS 'deleted', sub.ID AS 'subPageID', sub.page_title_EN AS 'title',
    sub.short_title_EN AS 'shortTitle', main.ID AS 'pageID', main.page_ASP, sub.page_text_EN 
FROM
    sub_items AS sub
INNER JOIN
    sub_menu AS main
    ON sub.subID = main.ID
WHERE
    sub.page_title_EN LIKE '%europe%'
    OR sub.page_text_EN LIKE '%europe%'
    OR sub.short_title_EN LIKE '%europe%'
    AND sub.active = 1
    AND sub.deleted = 0

2 个答案:

答案 0 :(得分:1)

假设对于每个活动主页面,应至少有一个活动子页面......

SELECT
    main.active, main.deleted, main.ID, main.page_ASP, main.page_title_EN, main.page_text_EN,
    sub.active, sub.deleted, sub.ID, sub.page_title_EN, sub.short_title_EN, sub.page_text_EN 
FROM
    sub_menu AS main
INNER JOIN
    sub_items AS sub
    ON sub.subID = main.ID
WHERE
    (main.page_title_EN LIKE '%europe%'
    OR main.page_text_EN LIKE '%europe%'
    OR sub.page_title_EN LIKE '%europe%'
    OR sub.page_text_EN LIKE '%europe%'
    OR sub.short_title_EN LIKE '%europe%'
    )
    AND main.active = 1
    AND main.deleted = 0
    AND sub.active = 1
    AND sub.deleted = 0

如果可以有一个没有子页面的活动主页面:

SELECT
    main.active, main.deleted, main.ID, main.page_ASP, main.page_title_EN, main.page_text_EN,
    sub.active, sub.deleted, sub.ID, sub.page_title_EN, sub.short_title_EN, sub.page_text_EN 
FROM
    sub_menu AS main
LEFT JOIN
    sub_items AS sub
    ON sub.subID = main.ID
WHERE
    (
        (main.page_title_EN LIKE '%europe%'
        OR main.page_text_EN LIKE '%europe%')
    AND 
        (main.active = 1 AND main.deleted = 0)
    )
AND 
(
    (sub.active IS NULL) 
    OR
    (
        (sub.page_title_EN LIKE '%europe%'
        OR sub.page_text_EN LIKE '%europe%'
        OR sub.short_title_EN LIKE '%europe%') 
    AND 
        (sub.active = 1 AND sub.deleted = 0)
    )
 )

答案 1 :(得分:0)

感谢我的问题的答案,我找到了一个有效的解决方案!感谢所有(非常快)的帮助,这是我最初问题的答案。

SELECT ID AS  'Main ID', NULL AS  'subPageID', page_ASP AS  'ASP file', page_title_EN AS  'Title', NULL AS  'SubTitle', NULL AS  'short Title', page_text_EN AS  'Content'
FROM sub_menu
WHERE page_title_EN LIKE  '%test%'
OR page_text_EN LIKE  '%test%'
AND active =1
AND deleted =0

UNION 

SELECT main.ID, sub.ID, main.page_ASP, main.page_title_EN, sub.page_title_EN, sub.short_title_EN, sub.page_text_EN
FROM sub_items AS sub
INNER JOIN sub_menu AS main ON sub.subID = main.ID
WHERE sub.page_title_EN LIKE  '%test%'
OR sub.page_text_EN LIKE  '%test%'
OR sub.short_title_EN LIKE  '%test%'
AND sub.active =1
AND sub.deleted =0