如何在我的表中获取另一个表列?

时间:2012-03-23 11:47:53

标签: php mysql sql

我有两张桌子。唱片和别墅

记录表

ID, VID (Villa ID), NAME, PRICE

别墅表:

ID, NAME (Villa NAME), PHOTOS etc.

我使用这个SQL:

SELECT records.id, villa_name AS (SELECT name FROM villas WHERE id = records.vid), records.name 
FROM records WHERE records.id = 5

有什么问题?

2 个答案:

答案 0 :(得分:2)

尝试

SELECT records.id, records.name AS record_name, villas.name AS villa_name FROM records INNER JOIN villas ON records.vid = villas.id WHERE records.id = 5

编辑:Mark Ba​​nnister的建议,见下文。

答案 1 :(得分:1)

你应该在这里使用JOIN。

SELECT r.id, r.name, v.name
FROM records r
INNER JOIN villas v ON v.id = r.vid
WHERE records.id = 5;