SQLite:使用JOIN从两个父表中检索列

时间:2017-01-24 16:17:24

标签: join sqlite foreign-keys

我有两个父表引用联结表中的外键:

schoolA_courses (
id INTEGER PRIMARY KEY AUTOINCREMENT, 
course_prefix TEXT, 
course_number INTEGER, 
course_title TEXT

schoolB_courses (
id INTEGER PRIMARY KEY AUTOINCREMENT, 
course_prefix TEXT, 
course_number INTEGER, 
course_title TEXT, 
course_url TEXT)

schoolB_equivalencies (
equivalency_id INTEGER PRIMARY KEY AUTOINCREMENT, 
schoolA_id INTEGER NOT NULL, 
schoolB_id INTEGER NOT NULL, 
is_archived INTEGER NOT NULL, 
FOREIGN KEY (schoolA_id) REFERENCES schoolA_courses (id), 
FOREIGN KEY (schoolB_id) REFERENCES schoolB_courses (id), 
UNIQUE (schoolA_id, schoolB_id) ON CONFLICT IGNORE)  

我正在尝试从两个父表中匹配的行中选择所有列,但我的查询只返回 -

schoolB_courses.course_prefix,
schoolB_courses.course_number,
schoolB_courses.course_title,
schoolB_courses.course_url

- 从一个父表(schoolB)。如何修改我的查询以从BOTH表中检索指定的字段,例如

schoolA_courses.course_prefix,
schoolA_courses.course_number,
schoolA_courses.course_title,
schoolB_courses.course_prefix,
schoolB_courses.course_number,
schoolB_courses.course_title,
schoolB_courses.course_url

我正在使用的查询是:

SELECT 
    schoolA_courses.course_prefix,
    schoolA_courses.course_number,
    schoolA_courses.course_title,
    schoolB_courses.course_prefix,
    schoolB_courses.course_number,
    schoolB_courses.course_title,
    schoolB_courses.course_url
FROM schoolB_equivalencies
INNER JOIN schoolA_courses
ON schoolA_courses.id = schoolB_equivalencies.schoolA_id
INNER JOIN schoolB_courses
ON schoolB_courses.id = schoolB_equivalencies.schoolB_id');

查询结果为

array (size=2)
  0 => 
    array (size=4)
      'course_prefix' => string 'ARCH' (length=4)
      'course_number' => string '111' (length=3)
      'course_title' => string 'Introduction to Structures' (length=26)
      'course_url' => string 'www.google.com' (length=14)
  1 => 
    array (size=4)
      'course_prefix' => string 'ARCH' (length=4)
      'course_number' => string '111' (length=3)
      'course_title' => string 'Introduction to Structures' (length=26)
      'course_url' => string 'www.google.com' (length=14)

1 个答案:

答案 0 :(得分:1)

您用来访问数据库的语言(无论它是什么)不允许按索引访问列,并且会被相同的列名混淆。

使用AS重命名结果列:

SELECT 
    schoolA_courses.course_prefix AS A_prefix,
    schoolA_courses.course_number AS A_number,
    schoolA_courses.course_title  AS A_title,
    schoolB_courses.course_prefix AS B_prefix,
    ...