![](/img/trans.png)
[英]MySQL - change time values of one row to match time values of another row of the same table
[英]Match the values of a row in table with values in a column in another table
我有這2張桌子:
+---------------+--------+
| id1 | name |
+---------------+--------+
| 1 | test |
| 2 | teest |
| 3 | teeest |
+---------------+--------+
+-----+------------+---------+-----------+---------+
| id2 | date | morning | afternoon | evening |
+-----+------------+---------+-----------+---------+
| 1 | 2017-12-14 | 1 | 2 | 1 |
| 2 | 2017-12-15 | 2 | 1 | 3 |
+-----+------------+---------+-----------+---------+
所有我想要做的就是echo
,在一個PHP文件,第二個表的值,而是數字我想呼應他們的地方第一個表的名稱。
有人可以教我如何得出這個結果嗎?
編輯:當我使用此代碼:
<?php
$sql = mysqli_query($con, "SELECT * FROM table2");
while ($row = mysqli_fetch_array($sql)) {
echo "<center>" . $row['date'] . " " .$row['morning']. " " .$row['afternoon']. " " .$row['evening']. "</center>";
}
?>
我有結果
2017-12-14 1 2 1
2017-12-15 2 1 3
我想要這個代替:
2017-12-14 test teest test
2017-12-15 teest test teeest
謝謝。
從第一個表中的值選擇一個數組,並在顯示第二個表時,將第二個表的值用作鍵。
樣品:
$names = [1 => 'test', 2 => 'teest', 3 => 'teeest'];
echo $names[$secondrow["morning"]];
如果我理解正確...
最好的辦法是使具有INNODB
引擎的表之間具有表之間的關系,即在第二個表到第一個表之間定義的foreign key
。
然后,您將使用將要從兩個表接收數據的關系對數據庫運行SQL查詢,並在查詢的SELECT
部分中定義要顯示的列。
SELECT atable.name, btable.*
FROM btable
JOIN atable ON btable.name_id = atable.id;
這是我的示例: http : //sqlfiddle.com/#!9/e851e0/3
您應該使用JOIN
。
詢問
select
`t2`.`id2`,
`t2`.`date`,
`ta1`.`name` as `morning`,
`ta2`.`name` as `afternoon`,
`ta3`.`name` as `evening`
from `table2` as `t2`
join `table1` as `ta1`
on `ta1`.`id1` = `t2`.`morning`
join `table1` as `ta2`
on `ta2`.`id1` = `t2`.`afternoon`
join `table1` as `ta3`
on `ta3`.`id1` = `t2`.`evening`;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.