Mysql 具有不同表中字段的人员列表
我是关系数据库的新手。我的客户要求提供默认情况下具有不同字段的客户列表。但是在模式中,有8个不同的表,我需要为每个表列出字段 我正在考虑实现这样一个查询Mysql 具有不同表中字段的人员列表,mysql,sql,postgresql,Mysql,Sql,Postgresql,我是关系数据库的新手。我的客户要求提供默认情况下具有不同字段的客户列表。但是在模式中,有8个不同的表,我需要为每个表列出字段 我正在考虑实现这样一个查询 SELECT name, surname, country_of_birth, nationality, email from clients, client_documents as documents, client_addresses as address 有重复的字段,但我不知道如何使用相同的uuid\u cli
SELECT name, surname, country_of_birth, nationality, email
from clients,
client_documents as documents,
client_addresses as address
有重复的字段,但我不知道如何使用相同的
uuid\u client
,它是每个表中的外键 您可以使用join
和更短的表别名
,这样您就更容易包含其列
select t1.name
, t1.surname
, t1.country_of_birth
, t1.nationality
, t1.email
, t2.documents
, t3.city
from clients t1
inner join client_documents t2 on t1.uuid_client = t2.uuid_client
inner join client_addresses t3 on t1.uuid_client = t3.uuid_client
从上面的查询来看,您似乎需要加入表。但是您没有提到其他表中的任何字段。因此,如果这些表中有任何公共字段,则可以使用join
或者您也可以尝试使用UNION
。
请详细说明你的问题。因此,我可以正确地回答它解决它的一种方法是使用
JOIN
。
例如:
SELECT clients.name, clients.surname, address.country_of_birth, clients.nationality, clients.email
FROM clients clients
LEFT JOIN client_documents AS documents on clients.id = documents.client_id
LEFT JOIN client_addresses AS address on clients.id = address.client_id
我建议在这种情况下使用LEFT-JOIN,因为如果我们使用(内部)JOIN,您无法看到客户机没有地址或文档信息。所以我们使用了LEFT-join,但正如我所说的,选择取决于您的场景。您使用的是MySQL还是Postgresql?“今天的提示:始终使用现代的显式
join
语法。更容易写(没有错误),更容易阅读和维护,如果需要,更容易转换为外部连接!顺便说一句,表有列,而不是字段。当前查询缺少什么?当涉及多个表时,最好的编程实践是限定所有列,例如客户端。name
而不仅仅是name
。教TS选择有意义的表别名,例如客户端的c
等等,与a、b、c相比,我更喜欢使用它,比如订单、订单详细信息、订单摘要,因此需要额外的字母缩写,与t1、t2、t3不同,我知道我的第一个表是t1,第二个联接表是t2..等等
SELECT clients.name, clients.surname, address.country_of_birth, clients.nationality, clients.email
FROM clients clients
LEFT JOIN client_documents AS documents on clients.id = documents.client_id
LEFT JOIN client_addresses AS address on clients.id = address.client_id