我有两个桌子。
1-汽车(列:ID,名称,描述,图像)
2-摩托车(列:ID,名称,描述,图像)
我想在Vehicles.php页面上循环两个表。我想按循环中的ID排序。
我的代码
CARS
$cars= $baglan->query("SELECT * FROM Cars ORDER BY id", PDO::FETCH_ASSOC);
if ( $cars->rowCount() )
foreach( $cars as $car){
-
}}
摩托车
$query= $baglan->query("SELECT * FROM Motorcycles ORDER BY id", PDO::FETCH_ASSOC);
if ( $query->rowCount() )
foreach( $query as $row){
-
}}
如何合并这两个查询?
此代码无效
$vehicles= $baglan->query("SELECT * FROM Motorcycles , Cars ORDER BY id", PDO::FETCH_ASSOC);
if ( $vehicles->rowCount() )
foreach( $vehicles as $vehicle){
-
}}
谢谢
答案 0 :(得分:1)
由于它们具有相同的列,因此您可以使用MATCH (n:Owner)
WHERE (n)-[:OWNS]->(:Vehicles)
RETURN DISTINCT n.email, n.name
ORDER BY n.name
UNION
答案 1 :(得分:1)
如果要在一个查询中合并它们,则可以在mysql中使用UNION
,但我强烈建议您仅在两个表的列相同的情况下使用它。
try {
$vehicles = $baglan->query("
SET @id:=0;
SELECT (@id:=@id+1) AS `ID`,`Name`,`Description`,`Image` FROM (
(SELECT * FROM `Cars` ORDER BY `ID`)
UNION
(SELECT * FROM `Motorcycles` ORDER BY `ID`)
) AS `Vehicles`;
", PDO::FETCH_ASSOC);
if ($vehicles->rowCount()) {
$id = 1;
foreach($vehicles as $vehicle) {
echo $id++; // Use $id because the `id` column is from two tables
// use other fields normally
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
但是,如果您想在原始ID列上排序混合数据,则可以使用它(例如,降序):
try {
$vehicles = $baglan->query("
SELECT * FROM (
(SELECT * FROM `Cars` ORDER BY `ID` DESC)
UNION
(SELECT * FROM `Motorcycles` ORDER BY `ID` DESC)
) AS `Vehicles`
ORDER BY `ID` DESC;
", PDO::FETCH_ASSOC);
if ($vehicles->rowCount()) {
$id = 1;
foreach($vehicles as $vehicle) {
echo $id++; // Use $id because the `id` column is from two tables
// use other fields normally
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
答案 2 :(得分:0)
您可以使用以下查询:
SELECT * FROM(
SELECT * FROM Motorcycles
UNION
SELECT * FROM Cars)
ORDER BY ID