在Mysql之后UNION SELECT $ stmt。我从多个表中获取数据,现在任务是从实际表中选择id
我以前得到的数据是
$stmt = $DB_con->prepare('SELECT * FROM city UNION SELECT * FROM fruit ORDER BY CreatedTime ASC LIMIT 15');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
echo $ id; echo $ userName;
我得到了类似的数据 1 - hyderavbads 2 - 香蕉 3 - 橙色 4 - 德里
现在我需要选择实际的id并从原始表中获取值
答案 0 :(得分:0)
使用当前查询无法从联合结果中了解原始表。
您可能希望将查询更改为此类内容,以便了解该ID的原始表格
SELECT id,value,'city' as tblName FROM city UNION SELECT id,value,'fruit' as tblName FROM fruit
答案 1 :(得分:0)
尝试下面的代码,这是逻辑如何实现,检查并告诉我们是否有任何问题。
mysql> create table city(id int, city_name varchar(20));
Query OK, 0 rows affected (0.35 sec)
mysql> create table fruits(id int, fruit_name varchar(20));
Query OK, 0 rows affected (0.40 sec)
mysql> insert into city values(1,'Hyderabad');
Query OK, 1 row affected (0.04 sec)
mysql> insert into fruits values(1,'Banana');
Query OK, 1 row affected (0.06 sec)
mysql> SELECT id,city_name,'city' source FROM city UNION SELECT id,fruit_name,'fruits' FROM fruits;
+------+-----------+--------+
| id | city_name | source |
+------+-----------+--------+
| 1 | Hyderabad | city |
| 1 | Banana | fruits |
+------+-----------+--------+
2 rows in set (0.01 sec)
$stmt = $DB_con->prepare('SELECT id,city_name FROM city UNION SELECT id,fruit_name FROM fruit ORDER BY CreatedTime ASC LIMIT 15');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
---write here a case/if statement like
If($source=="city")
{
--again prepare the statement and select the data from city table like
$stmt_city = $DB_con->prepare('SELECT id,city_name,other_col_val FROM city where id = $id');
}
else
{
--again prepare the statement and select the data from fruits table like
$stmt_city = $DB_con->prepare('SELECT id,fruit_name,other_col_val FROM fruits where id = $id');
}
}
}