SQLite加入帮助

时间:2011-08-11 22:13:21

标签: sql sqlite join

考虑这个表结构

people{id,firstName,lastName,preferredName}
list{id,person1_id,person2_id}

我希望从列表中获取所有数据,但是要使用人员的姓名而不是ID并扭曲:如果设置了preferredName,请使用它,否则请使用firstName+SPACE+lastName

如果我只需要一个名字,那么查询将是:

SELECT list.id,
CASE WHEN people.preferredName IS NULL OR people.preferredName="" THEN people.firstName||' '||people.lastName ELSE people.preferredName END AS preferredName 
FROM list LEFT JOIN people ON list.person1_id=people.id;

谢谢。

2 个答案:

答案 0 :(得分:2)

COALESCE()返回其第一个非null参数。

COALESCE(preferredName, firstName || ' ' || lastName) as person_name

我认为你不需要左连接,但我可能错了。 (如果您有外键约束,使得person1_id和person2_id必须存在于人员中,则不需要左连接。)

SELECT list.id,
COALESCE( p1.preferredName, p1.firstName || ' ' || p1.lastName) as person1_name,
COALESCE( p2.preferredName, p2.firstName || ' ' || p2.lastName) as person2_name,
FROM list 
INNER JOIN people p1 ON list.person1_id= p1.id
INNER JOIN people p2 on list.person2_id = p2.id

答案 1 :(得分:1)

使用表别名可以将同一个表连接两次。

SELECT list.id,
       CASE WHEN people1.preferredName IS NULL OR people1.preferredName = ""
         THEN people1.firstName || ' ' || people1.lastName
         ELSE people1.preferredName
       END AS preferredName1,
       CASE WHEN people2.preferredName IS NULL OR people2.preferredName = ""
         THEN people2.firstName || ' ' || people2.lastName
         ELSE people2.preferredName
       END AS preferredName2,
  FROM list
  LEFT JOIN people people1 ON list.person1_id = people1.id
  LEFT JOIN people people2 ON list.person2_id = people2.id