我有一个程序可以从源代码和外部源代码下载信息,并为我输入的每个查询提供了一个sql页面。通常,每个标题都有3到6个查询。 每个sql页面都会加载一个新表,并且所有表都具有相同的列。下面是查询UsedCar和NewCar的结果示例,它是Title Automotive中涉及的6个查询中的2个。
CREATE TABLE IF NOT EXISTS NewCar(Name char(255) DEFAULT NULL,
Phone char(255) DEFAULT NULL,
Address char(255) DEFAULT NULL,
Website char(255) DEFAULT NULL,
Email char(255) DEFAULT NULL,
Category char(255) DEFAULT NULL,
UNIQUE KEY Name (Name))
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
LOCK TABLES NewCar WRITE;
REPLACE INTO NewCar VALUES('whats it Auto','1-888-555-7327','63 Beech Hill Rd, Beechville, NS B1G 2R9','http://www.whatsit.com','','New Car Dealers');
REPLACE INTO NewCar VALUES('Hugh\'s Chev','888-555-6990','376 Main St, lower bohemia, NS B5G 2D6','','','New Car Dealer');
REPLACE INTO NewCar VALUES('Be It Motors Ltd','866-555-2771','90 Main St, Upper Bohemia, NS B9G 2K8','','','New Car Dealers');
UNLOCK TABLES;
CREATE TABLE IF NOT EXISTS UsedCar(Name char(255) DEFAULT NULL,
Phone char(255) DEFAULT NULL,
Address char(255) DEFAULT NULL,
Website char(255) DEFAULT NULL,
Email char(255) DEFAULT NULL,
Category char(255) DEFAULT NULL,
UNIQUE KEY Name (Name))
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
LOCK TABLES UsedCar WRITE;
REPLACE INTO UsedCar VALUES('whats it Auto','1-888-555-7327','63 Beech Hill Rd, Beechville, NS B1G 2R9','http://www.whatsit.com','','Used Car Dealers');
REPLACE INTO UsedCar VALUES('Hugh\'s Chev','888-555-6990','376 Main St, lower bohemia, NS B5G 2D6','','','Used Car Dealer');
REPLACE INTO UsedCar VALUES('Be It Motors Ltd','866-555-2771','90 Main St, Upper Bohemia, NS B9G 2K8','','','Used Car Dealers');
UNLOCK TABLES;
然后将它们加载到我的数据库中。
我的问题是尝试将此信息提取到我的网页中。我想创建一个链接,在“汽车”下显示“类别”下的唯一信息。我可以从一个表中执行此操作,但无法为多个表执行此操作。 我试过研究这个问题,并尝试选择DISTINCT和UNIQUE。和表JOIN和UNION一样 - 我确信这可能是我忘记的非常愚蠢的事情。
下面是我用来从单个表中绘制的PHP,该表已被修改为试图从2个表中绘制并返回“未找到记录”。
<?php
$result = mysql_query("SELECT DISTINCT Name FROM (SELECT * FROM UsedCar UNION SELECT*FROM NewCar) ORDER BY name ASC");
if(mysql_num_rows($result) == 0){
echo("no records found");
} ELSE {
echo "<table border='0'; table id='address'>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Address</th>
<th>Website</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Phone'] . "</td>";
echo "<td>" . $row['Address'] . "</td>";
echo '<td><a href="' . $row['Website'] . '" target="_self\">' . $row["Website"] . '</a></td>';
echo "</tr>";
}
echo "</table>";
}
?>
很抱歉很长的帖子.. :)
答案 0 :(得分:2)
部分问题是您的SQL语法,您缺少子选择
上的别名您没有别名查询(请参阅SQL Fiddle):
SELECT DISTINCT Name
FROM
(
SELECT *
FROM UsedCar
UNION
SELECT *
FROM NewCar
)
ORDER BY name ASC
使用别名(请参阅SQL Fiddle)
SELECT DISTINCT Name
FROM
(
SELECT *
FROM UsedCar
UNION
SELECT *
FROM NewCar
) x
ORDER BY name ASC
但如果你只想要这个名字,那么你就不需要子查询(见SQL Fiddle):
SELECT name
FROM UsedCar
UNION
SELECT name
FROM NewCar