从多个表中检索所有内容

时间:2012-10-07 04:31:57

标签: mysql

我有两张桌子:

Appointments
id serviceId
1  1
2  1

Services
id
1

通过使用serviceId列,约会表链接到服务表。从约会表中检索数据时,我还想从服务表中检索数据,但每个表中的列数不匹配。

我试过这个:

SELECT appointments.*, services.* FROM appointments
INNER JOIN services ON id = appointments.serviceId
WHERE id = ?

但这不起作用。首先,在连接中,如何从约会表中引用我尚未检索数据的ID?其次,如果两个列名称匹配,如何从两个表中获取所有数据然后检索数据?

这不起作用:

results.getInt("id");

因为两个表都有一个id字段。

1 个答案:

答案 0 :(得分:1)

指定ID所属的表名称

SELECT appointments.*, services.* 
FROM appointments
     INNER JOIN services 
         ON Services.id = appointments.serviceId
-- WHERE id = ? -- specify also here as the two tables have column ID

或在其周围添加ALIAS

SELECT  appointments.id as AppID,
        appointments.serviceId as AppServiceID
        services.id AS ServiceID
FROM    appointments
        INNER JOIN services
            ON Services.id = appointments.serviceId
-- WHERE   id = ?

当你得到它们的值时,现在就使用它们的别名,

results.getInt("AppID");