MySQL从表2中选择与表1相同
我有两个表
"employers":
emp_id empl_name wage
1 john 20/h
2 mike 20/h
3 sam 30/h
"positions":
pos_id emp_id pos_name related_pos
1 1 cleaner 0
2 3 driver 3
3 2 bodyguard 0
我需要显示表 雇主名称,职位名称,工资,相关职位名称,相对职位工资,相对职位雇主
现在我有疑问:
SELECT pos_name, empl_name, wage
FROM positions
LEFT JOIN employers ON employers.emp_id = positions.emp_id
下一个请求不起作用,但给出了我需要什么:
SELECT pos_name, empl_name, wage, (SELECT empl_name
FROM positions
LEFT JOIN employers ON employers.emp_id = positions.related_pos) as emp2,
(SELECT pos_name
FROM positions
WHERE pos_id = related_pos) as pos2
FROM positions
LEFT JOIN employers ON employers.emp_id = positions.emp_id
I have two tables
"employers":
emp_id empl_name wage
1 john 20/h
2 mike 20/h
3 sam 30/h
"positions":
pos_id emp_id pos_name related_pos
1 1 cleaner 0
2 3 driver 3
3 2 bodyguard 0
I need display table with
Employer Name, Position Name, Wage, Related Position Name, Rel Pos Wage, Rel Pos Employer
Now i have query:
SELECT pos_name, empl_name, wage
FROM positions
LEFT JOIN employers ON employers.emp_id = positions.emp_id
next rquest does not work, but gives idea of what i need:
SELECT pos_name, empl_name, wage, (SELECT empl_name
FROM positions
LEFT JOIN employers ON employers.emp_id = positions.related_pos) as emp2,
(SELECT pos_name
FROM positions
WHERE pos_id = related_pos) as pos2
FROM positions
LEFT JOIN employers ON employers.emp_id = positions.emp_id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这段代码可以完成这项工作。
我删除了以下代码。
因为我认为有两个错误。首先,表中没有
empl_name
列。其次,这个子查询将给出比一行更多的结果。当
emp_id
有多个条目时,这也适用于第一个子查询I think this code will do the work.
I removed the following code.
Because I think there are two errors. First there is no
empl_name
column in the table. Second this Subquery will give more then on result for a row.This also applies for the fist Subquery, when there is more then one entry for a
emp_id
看起来你只是让事情变得比需要的更复杂。如果我理解正确的话,您正在寻找链接表。将其分为三个部分:
您的选择应包括雇主名称、职位名称、工资、相关职位名称、相对职位工资、
来自雇主的相对职位雇主、职位,其中
职位.emp_id =雇主.emp_id
这将为您提供所有内容的列表雇主提供的与职位相匹配的项目。
抱歉,如果这不是您的意思。如果是的话请点点头。
It seems like you've just made this more complicated than it needs to be. You're looking to link tables, if I understand correctly. Break this down into three parts:
Your SELECT should include Employer Name, Position Name, Wage, Related Position Name, Rel Pos Wage, Rel Pos Employer
FROM employers, positions
WHERE positions.emp_id = employers.emp_id
This will get you a list of all the items from employers as they pair up with positions.
Sorry if this isn't what you meant. Give me a nod if it is.