使用内部联接在SELECT中设置别名

时间:2019-05-13 20:17:13

标签: mysql

我有2张桌子:

人物表:

id  |  name |  date
1   |  Mika |  2013
2   |  Rose |  2015

工作表:

id  |  user_id  |  work_name  |  registers
1   |     1     |    rugby    |     10
2   |     1     |    golf     |      3

我使用此查询来联接表:

SELECT * FROM work INNER JOIN people ON work.user_id = people.id WHERE work_name= :work_name

这可以工作,但是当我尝试打印阵营ID时,却得到了重复的列ID和php,这显示了最后一个列ID。 我尝试使用此方法,但不起作用:

SELECT *, id AS 'work_id' 
FROM work 
INNER JOIN people ON work.user_id = people.id 
WHERE work_name= :work_name

2 个答案:

答案 0 :(得分:1)

这是因为您正在*中使用SELECT,这意味着将从两个表中带走所有字段,而您可以使用

SELECT   work.id  as work_id, 
         work.name as work_name, 
         work.date as work_date,
         people.id as people_id, 
         people.name as people_name, 
         people.date as people_date

答案 1 :(得分:0)

尝试手动列出您需要显示的所有列,例如

SELECT w.user_id, w.work_name, w.registers, p.name, p.date FROM work as w INNER JOIN people as p ON work.user_id = people.id WHERE work_name= :work_name