假设我有两个表,并且两个表的主要标识符都使用名称"id".如果要对这两个表执行联接,该如何别名要与前一个表联接的表的id?
Let's say I have two tables, and both their primary identifiers use the name 'id'. If I want to perform a join with these two tables, how would I alias the id of the table that I want to join with the former table?
例如:
SELECT * FROM `sites_indexed` LEFT JOIN `individual_data` ON `sites_indexed`.`id` = `individual_data`.`site_id` WHERE `url` LIKE :url现在,site_id应该与sites_indexed.id链接.代表individual_data行的实际id与sites_indexed具有相同的 title .
Now, site_id is supposed to link up with sites_indexed.id. The actual id which represents the row for individual_data however has the same title as sites_indexed.
就个人而言,我喜欢为所有内容使用名称id,因为它可以使内容保持一致.但是,在对服务器端进行脚本编写时,这会使事情变得混乱.
Personally, I like to just use the name id for everything, as it keeps things consistent. When scripting server-side however, it can make things confusing.
例如
$var = $result['id'];
鉴于上述查询,这不会使解释器感到困惑吗?
Given the aforementioned query, wouldn't this confuse the interpreter?
无论如何,这是如何完成的?
Anyway, how is this accomplished?
推荐答案而不是使用"SELECT *"选择所有字段,而应显式命名所需的每个字段,并根据需要使用AS对其进行别名.例如:
Instead of selecting all fields with "SELECT *" you should explicitly name each field you need, aliasing them with AS as required. For example:
SELECT si.field1 as si_field1, si.field2 as si_field2, ind_data.field1 as ind_data_field1 FROM sites_indexed as si LEFT JOIN individual_data as ind_data ON si.id = ind_data.site_id WHERE `url` LIKE :url然后您可以在结果集中引用别名.
And then you can reference the aliased names in your result set.
更多推荐
别名左联接上的列名
发布评论