使用 UNION 的 PHP MySQL 查询并定位数据来自哪个表 [英] PHP MySQL query using UNIONs and locating which table the data came from
问题描述
所以我有一个查询,我从两个不同的表中选择值并将它们联合在一起.我需要知道哪个条目来自哪里,因为我需要为每个条目形成不同的 URL.标记这两个 SELECT 查询的最佳方法和正确语法是什么.任何帮助,将不胜感激.要遵循的代码:
So I have a query that I am selecting values from two different tables and UNIONizing them together. I need to know where which entry came from as I need to form a different URL for each. What is the best way and proper syntax to tag both of these SELECT queries. Any help would be appreciated. Code to follow:
$query = "SELECT newsletter_id id, newstitle title FROM tbl_news WHERE (newstitle LIKE '%".stripslashes($rowCont->fname)."%' && newstitle LIKE '%".stripslashes($rowCont->lname)."%') || (newsletter_content LIKE '%".stripslashes($rowCont->fname)."%' && newsletter_content LIKE '%".stripslashes($rowCont->lname)."%') SET @type = news
UNION
SELECT event_id id, event_title title FROM tbl_event WHERE ((event_title LIKE '%".stripslashes($rowCont->fname)."%' && event_title LIKE '%".stripslashes($rowCont->lname)."%') || (event_content LIKE '%".stripslashes($rowCont->fname)."%' && event_content LIKE '%".stripslashes($rowCont->lname)."%')) SET @type = event";
$result = mysql_query($query) or die(mysql_error());
$i = 0;
while($row = mysql_fetch_assoc($result)) {
if($table_name == table1) { //SIMULATED TABLE NAME VARIABLE IF STATEMENT, NEED TO KNOW HOW TO GET TABLE NAME FOR SORTING
echo "<p><a style='color:#00aeef' href='http://www.url1.com/display.php?article_=".$row["id"]."'>".$row["title"]."</a></p>";
} else {
echo "<p><a style='color:#00aeef' href='http://www.url1.com/display.php?article_=".$row["id"]."'>".$row["title"]."</a></p>";
}
}
推荐答案
一个选项是在每个查询的选择列表中包含一个文字,例如:
One option is to include a literal in the select list of each query, for example:
SELECT 'q1' AS source, newsletter_id id, ...
UNION
SELECT 'q2' AS source, event_id id, ...
<小时>
顺便说一句,如果不需要删除重复项,请考虑使用 UNION ALL
运算符代替 UNION
运算符.
As an aside, consider using UNION ALL
operator in place of the UNION
operator, if removing duplicates is not a requirement.
这篇关于使用 UNION 的 PHP MySQL 查询并定位数据来自哪个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!