如何根据关系数据库模式编写SQL查询?

问题描述 投票:0回答:1

首先: 图 1 中的粗体属性(即 ID)(见下文)是主键。 由于我不太确定我提出的要求和其他类型的解释有多好,因此请不要要求进一步澄清。 publicMessage 实体仅存储在虚拟公共场所(即 WhatsApp 群组)传输的消息 privateMessage 实体仅存储用户彼此私下单独发送的私人消息。 pID1 代表发送者,而 pID2 代表接收者。 然而,我创建了这个查询,当我把它写在一张纸上时,我没有机会有效地运行它。

考虑以下关系数据库模式:

person(**ID**, firstName, lastName, nickName)
follows(**pID1**, **pID2**)
publicMessage(**ID**, pID, date, text)
privateMessage(**ID**, pID1, pID2, date, text)

要求 我想编写一个 SQL 查询,列出所有向具有相同名字的人发送私人消息的人(ID 和名字)。换句话说,查询应该只检索向“他们自己”或“其他拥有相同名字的接收者”发送“私人消息”的人。 01.SELECT DISTINCT p1.ID, p1.firstName 02.FROM person p1 03.JOIN privateMessage pm ON p1.ID = pm.pID1 04.JOIN person p2 ON pm.pID2 = p2.ID 05.WHERE p1.firstName = p2.firstName 06.OR pm.pID1 = pm.pID2; 01.I used the **DISTINCT** statement to eliminate name repetitions. 02.I used the JOIN clause to connect the person table with the privateMessage table twice (as p1 and p2) based on the sender (pID1) and receiver (pID2) IDs. 05.The WHERE clause ensures that I only include rows where the first names match between the sender (p1) and receiver (p2) or if the sender is sending a private message to themselves (pm.pID1 = pm.pID2). 问题:

您在上述查询中指出的问题是否有任何错误?
您是否有更“优雅/高效”的代码可以更有效地检索名称?

    提前谢谢您!
  1. 我的做法与您几乎相同,但没有使用不同的。这是 PostgreSQL 15 上的。

create table person( id INT generated always as identity primary key, firstName varchar(12), lastName varchar(12), nickName varchar(12)) ; create table privateMessage( id INT generated always as identity primary key, sender_id integer, receiver_id integer, date date, message_text varchar(32), constraint fk04 foreign key(sender_id) references person(id), constraint fk05 foreign key(receiver_id) references person(id) ) ;

sql mysql relational-database
1个回答
0
投票

insert into person (firstName, lastName, nickName) values ('Alice', 'Smith', ''); /* pk 1 */ insert into person (firstName, lastName, nickName) values ('Bob', 'Jones', ''); /* pk 2 */ insert into person (firstName, lastName, nickName) values ('Alice', 'Young', ''); /* pk 3 */

创建几条消息:

insert into privateMessage (sender_id, receiver_id, message_text) values (1, 1, 'message text 1'); insert into privateMessage (sender_id, receiver_id, message_text) values (1, 2, 'message text 2'); insert into privateMessage (sender_id, receiver_id, message_text) values (1, 3, 'message text 3'); insert into privateMessage (sender_id, receiver_id, message_text) values (2, 1, 'message text 4');

查询数据:

select p1.firstName || ' ' || p1.lastName as sender_name, p2.firstName || ' ' || p2.lastName as receiver_name, pm1.message_text as message_text from person p1, person p2, privateMessage pm1 where p1.firstName = p2.firstName and pm1.sender_id = p1.id and pm1.receiver_id = p2.id ;

结果:

sender_name receiver_name message_text Alice Smith Alice Smith message text 1 Alice Smith Alice Young message text 3

© www.soinside.com 2019 - 2024. All rights reserved.