将两个查询合并为一个

时间:2015-02-02 08:31:33

标签: mysql

这是我的代码:

$queryresult="SELECT a.ArticleID, a.Title, a.Publication, l.EnglishLanguage, m.EnglishMedia, a.PublicationYear, a.Size , REPLACE( GROUP_CONCAT( DISTINCT REPLACE( c.EnglishCategory, ',',  '' ) ) ,  '/',  ',' ) ,  GROUP_CONCAT( DISTINCT au.EnglishName,  '/' ), GROUP_CONCAT( DISTINCT au.PictureURL ) , a.Abstract,a.URL,m.IconURL,REPLACE( GROUP_CONCAT( DISTINCT REPLACE( au.EnglishName,  ',',  '' ) ) ,  '/',  ',' )
FROM article a
LEFT JOIN aritcletocategory ac ON a.ArticleID = ac.ArticleID
LEFT JOIN category c ON ac.CategoryID = c.CategoryID
LEFT JOIN articletoauthor at ON a.ArticleID = at.ArticleID
JOIN MediaType m ON a.MediaTypeID = m.MediaTypeID
JOIN Language l ON a.LanguageID = l.LanguageID
LEFT JOIN author au ON at.AuthorID = au.AuthorID
WHERE a.Title REGEXP '".$search."' || replace(au.EnglishName,',','') REGEXP '".$search."' || replace(au.HebrewName,',','') REGEXP '".$search."' || a.Keywords REGEXP '".$search."'|| c.EnglishCategory REGEXP '".$search."' || a.Abstract REGEXP '".$search."'|| a.Publication REGEXP '".$search."'GROUP BY a.ArticleID";
$finalresult=show_result($queryresult);

我从此查询的结果中获得的ID用于以下查询:

foreach($finalresult as $ress){
$queryresults="SELECT a.ArticleID, a.Title, a.Publication, l.EnglishLanguage, m.EnglishMedia, a.PublicationYear, a.Size , REPLACE( GROUP_CONCAT( DISTINCT REPLACE( c.EnglishCategory,  ',',  '' ) ) ,  '/',  ',' ) , GROUP_CONCAT( DISTINCT au.EnglishName ,  '/' ), GROUP_CONCAT( au.PictureURL ) , a.Abstract,a.URL, REPLACE( GROUP_CONCAT( DISTINCT REPLACE( au.HebrewName,  ',',  '' ) ) ,  '/',  ',' ),m.IconURL,REPLACE( GROUP_CONCAT( DISTINCT REPLACE( au.EnglishName,  ',',  '' ) ) ,  '/',  ',' )
FROM article a
LEFT JOIN aritcletocategory ac ON a.ArticleID = ac.ArticleID
LEFT JOIN category c ON ac.CategoryID = c.CategoryID
LEFT JOIN articletoauthor at ON a.ArticleID = at.ArticleID
LEFT JOIN author au ON at.AuthorID = au.AuthorID
JOIN MediaType m ON a.MediaTypeID = m.MediaTypeID
JOIN Language l ON a.LanguageID = l.LanguageID
WHERE a.ArticleID =".$ress[0]." GROUP BY a.ArticleID ";
$finalresults=show_result($queryresults);

我希望通过一个查询而不是使用两个查询来获得结果。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

由于您的查询具有相同的结构,因此您可以使用UNION

--Query 1
SELECT ...

UNION

--Query 2
SELECT ...

;

查看w3schools - SQL UNION Operator了解详情。

或者如果您想获得更多专业信息:MySQL Manual: Union Syntax