繁体   English   中英

在Mysql UNION SELECT $ stmt ..之后,我从多个表中获取了数据

[英]after Mysql UNION SELECT $stmt .. i got data from multiple tables

在Mysql UNION之后选择$ 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);

回声$ id; echo $ userName;

我得到了像1的数据-海德拉巴德2-香蕉3-橙4-德里

现在我需要选择实际的id并从原始表中获取值

您无法使用当前查询从该联合结果中了解原始表。

您可能需要将查询更改为类似的内容,以便您知道该ID的原始表在哪里

SELECT id,value,'city' as tblName FROM city UNION SELECT id,value,'fruit' as tblName FROM fruit

试试下面的代码,这是如何实现,签出并让我们知道是否有任何问题的逻辑。

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');
    }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM