需要帮助加入表格

时间:2008-11-25 03:35:09

标签: mysql join

我有一个将表导出为CSV的函数,在查询中我设置了哪些字段将导出。

以下是查询:

SELECT lname, fname, email, address1, address2, city, 
state, zip, venue_id, dtelephone, etelephone, tshirt FROM volunteers_2009

field venue_id是场地的id,在另一张桌子(场地)中提及

所以志愿者_2009.venue_id = venues.id

当我打开CSV文件时,它会显示我理解的venue_id,但我需要帮助修改查询以在CSV文件中输入场地名称(venues.venue_name)。

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

SELECT a.lname, a.fname,a. email, a.address1,a. address2, a.city, 
    a.state, a.zip, a.venue_id, a.dtelephone, a.etelephone, a.tshirt,
    COALESCE(b.venue_name,'') AS VenueName
FROM volunteers_2009 a
LEFT JOIN venues b ON b.id=a.venue_id

答案 1 :(得分:0)

标准SQL查询是(假设您需要场地的ID和名称):

SELECT a.lname as lname, a.fname as fname, a.email as email,
    a.address1 as address1, a.address2 as address2, a.city as city, 
    a.state as state, a.zip as zip, a.venue_id as venue_id,
    b.venue_name as venue_name, a.dtelephone as dtelephone,
    a.etelephone as etelephone, a.tshirt as tshirt
FROM volunteers_2009 a, venues b
WHERE a.venue_id = b.id
AND a.venue_id IS NOT NULL
UNION ALL
SELECT a.lname as lname, a.fname as fname, a.email as email,
    a.address1 as address1, a.address2 as address2, a.city as city, 
    a.state as state, a.zip as zip, a.venue_id as venue_id,
    '' as venue_name, a.dtelephone as dtelephone,
    a.etelephone as etelephone, a.tshirt as tshirt
FROM volunteers_2009 a
WHERE a.venue_id IS NULL

答案 2 :(得分:0)

SELECT lname, fname, email, address1, address2, city,   
state, zip, b.venue_name, dtelephone, etelephone, tshirt FROM   
volunteers_2009 a, venues b  
where a.venue_id = b. venue_id

如果两个表都有任何具有相同名称的列,请使用正确的别名。

---编辑让场地的所有行都使用外部联接

SELECT lname, fname, email, address1, address2, city,   
state, zip, b.venue_name, dtelephone, etelephone, tshirt FROM  
volunteers_2009 a(+), venues b  
where a.venue_id = b. venue_id