【问题标题】:SQL - Multiple select statements, one column, one querySQL - 多个选择语句,一列,一个查询
【发布时间】:2013-03-01 16:41:00
【问题描述】:

我有一个名为 person 的表,它有一个名为 person_id 的主键。 person 表包含有关患者和医生的信息(姓名首字母、姓氏等)。我还有另一个名为约会的表,其中包含医生 ID、患者 ID 和有关约会的信息。 Doctor_id 和 Patient_id 与 person 表中的 person_id 相关联。

我需要进行一个查询,该查询将返回医生的姓名(使用带有首字母和姓氏的 concat)和患者的姓名。

我尝试过使用嵌套的 select 语句,但没有成功..

任何信息都会很棒!

丹

【问题讨论】:

  • 你必须在persons表上自我加入两次
  • 要么,要么包括选择作为我不喜欢的列=)
  • 你在用什么RDBMS? RDBMS 代表关系数据库管理系统。 RDBMS is the basis for SQL,适用于所有现代数据库系统,如 MS SQL Server、IBM DB2、Oracle、MySQL 等...

标签: sql select join


【解决方案1】:
SELECT d.initials + ' ' + d.last_name AS 'doctor name', p. initials + ' ' + p.last_name AS 'patient name'
FROM Person p
INNER JOIN appointment a
ON p.person_id = a.patient_id
INNER JOIN Person d
ON d.person_id = a.doctor_id

【讨论】:

  • 当我将 "d.initials + ' ' + d.last_name" 替换为 "CONCAT(d.initials,' ',d.last_name)" 时效果很好。由于某种原因,您的返回 0。非常感谢!
【解决方案2】:

在 SQL Server 中,连接是通过使用 + 运算符完成的。所以连接运算符取决于您使用的 RDBMS。 (在MYSQL 中,使用CONCAT 运算符)

基本上,您需要在表appointment 上连接表person 两次,因为有两列依赖于表person。

SELECT  a.*
        doc.firstName + ' ' + doc.lastName as DoctorName,
        pat.firstName + ' ' + pat.lastName as PatientName
FROM    appointment a
        INNER JOIN person doc
            ON a.person_ID = doc.doctor_ID
        INNER JOIN person pat
            ON a.person_ID = pat.patient_ID

如需进一步了解联接,请访问以下链接:

【讨论】:

  • 感谢您的回复和链接。需要了解连接。
  • 既然你用的是MySQL,那就应该是CONCAT(doc.firstName, ' ', doc.lastName)
【解决方案3】:

从这里开始:

select 
  patient.person_id, 
  doctor.person_id
from person as patient
left join appointment 
    on appointment.patient_id = patient.person_id
left join person as doctor 
    on doctor.person_id = appointment.doctor_id 
   and doctor.person_id = patient.doctor_id

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2015-11-05
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    相关资源
    最近更新 更多