gpt4 book ai didi

php - 从一个mysql中选择多个表

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:27 25 4
gpt4 key购买 nike

我有一个名为atp2 的mysql 数据库。基本上它保存了过去 7 年所有网球比赛的所有结果。但是,每年都在不同的表格下。所以我有 7 张 table 。 2010 年、2011 年、2012 年、2013 年、2014 年、2015 年、2016 年、2017 年。但每次我想做一个问题时,我都想同时在所有表上运行它。所以我做了这样的 connection.php。

 $db = new mysqli("xxx", "xxx", "xxx", "2012");

有没有一种方法可以让我选择 connection.php 中的所有表,而不必一个一个地选择它们?表中的所有列名都相同。如果有另一种更简单的方法,比如加入所有表格,我也可以这样做,但我必须每天都这样做,因为 2017 年的表格每天都会更新。

根据下面的评论,我还有一个 head2head.php,我想在其中比较 2 个玩家之间的每场比赛。

<br>
<?php echo "Here are the matches " . $_POST[Player1] . " won vs " . $_POST[Player2]; ?> <br>
<?php
$sql = <<<SQL
select from ( SELECT *
FROM 2012
union all
SELECT *
FROM 2013
union all
SELECT *
FROM 2014
union all
SELECT *
FROM 2015
union all
SELECT *
FROM 2016
union all
SELECT *
FROM 2017 )
WHERE t.Winner = "$_POST[Player1]"
AND t.Loser = "$_POST[Player2]"
SQL;

if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}

// Output the rows
while($row = $result->fetch_assoc()){
echo $row[winner_name] . "-" . $row[loser_name] . "<br/>";
}
?>

最佳答案

如果表的结构(列位置、名称和数据类型)完全相同,您可以对所有表进行 se 和 union

    select col1, col2, col3 ....
from my_table2010
union all
select col1, col2, col3 ....
from my_table2011
union all
select col1, col2, col3 ....
from my_table2012
union all
select col1, col2, col3 ....
from my_table2013
union all
select col1, col2, col3 ....
from my_table2014
union all
...
select col1, col2, col3 ....
from my_table2017

用mysqli

你应该这样做

// Create connection
$conn = new mysqli($your_servername, $your_username, your_$password, $your_dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = " select col1, col2, col3 ....
from my_table2010
union all
select col1, col2, col3 ....
from my_table2011
union all
select col1, col2, col3 ....
from my_table2012
union all
select col1, col2, col3 ....
from my_table2013
union all
select col1, col2, col3 ....
from my_table2014
union all
select col1, col2, col3 ....
from my_table2015
union all
select col1, col2, col3 ....
from my_table2016
union all
select col1, col2, col3 ....
from my_table2017";

$result = $conn->query($sql);

在你的情况下

如果你需要过滤器(where)你应该使用这个语法

   <?php
$sql = "
select from ( SELECT *
FROM 2012
union all
SELECT *
FROM 2013
union all
SELECT *
FROM 2014
union all
SELECT *
FROM 2015
union all
SELECT *
FROM 2016
union all
SELECT *
FROM 2017 ) t
WHERE t.Winner = " . $_POST[Player1] . "
AND t.Loser = " . $_POST[Player2] ;

你错了有两个原因1- 因为在 union 之后所有的 sql 都需要 select 而不是 where ,,,2 - 如果你把 where 放在一个选择的底部,你只过滤这个选择而不是联合选择

关于php - 从一个mysql中选择多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42177422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com