简体   繁体   English

在 php-mysql 中加入 2 个或更多表

[英]Joining 2 or more tables in php-mysql

I want to join 2 or more table in my Hotel management project, so what all are the steps to join tables?我想在我的酒店管理项目中加入 2 个或更多表,那么加入表的所有步骤是什么? Is it necessary to give foreign key in each table we need to join or works without foreign key?是否有必要在我们需要加入的每个表中提供外键或在没有外键的情况下工作?

The steps are:步骤是:

  1. Write a JOIN query.编写一个JOIN查询。 You're done!你完成了!

You can JOIN using columns that are neither a primary key nor foreign key.您可以使用既不是主键也不是外键的列进行JOIN Eg,例如,

select *
from (select 'x' as a) t1
inner join (select 'x' as a) t2 on t1.a = t2.a

A query has a JOIN clause and an ON clause.一个查询有一个JOIN子句和一个ON子句。 The JOIN clause says what type of JOIN it is and which tables are being JOIN ed. JOIN子句说明它是什么类型的JOIN以及哪些表正在被JOIN ed。 The ON clause specifies which columns to JOIN on. ON子句指定要JOIN列。

No you don't need to use foreign keys specifically, although you will probably use an equivalent.不,您不需要专门使用外键,尽管您可能会使用等效的外键。 (note, the default engine MyISAM, does not support foreign keys, if you want to use them, use InnoDB or $otherEngine). (注意,默认引擎 MyISAM,不支持外键,如果你想使用它们,使用 InnoDB 或 $otherEngine)。

For joins I would suggest reading the documentation on joins .对于连接,我建议阅读有关 joins的文档

Simple join, without redundant ID output:简单连接,无冗余 ID 输出:

SELECT * FROM foo JOIN bar USING (id); SELECT * FROM foo JOIN bar USING (id);

Assuming the id column is defined in both tables as primary, hence creating the relationship between tables you want to join.假设 id 列在两个表中都被定义为主要的,因此在要连接的表之间创建关系。

However, there are different type of joins (natural, straight, left, right), based on what criteria and requirements you have.但是,根据您的标准和要求,有不同类型的连接(自然连接、直线连接、左连接、右连接)。 Check out the MySQL API manual, it will provide you with sufficient information.查看 MySQL API 手册,它将为您提供足够的信息。

我认为对于您的情况(如顶部帖子中所述),创建一个 PHP 文件来分别获取每个表的来宾数据会更有意义,至少对我而言,将 6 个表连接在一起似乎是太麻烦,而且在实际中不是很有效。

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

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