Mysql 列出两个表中的用户

Mysql 列出两个表中的用户,mysql,join,ascii,Mysql,Join,Ascii,嗨,我有用户_表1和用户_表2,我还有表格作业和雇主 当我从user_table1中获取用户并为他们获取工作和雇主信息时,我的请求就会起作用,但当我加入user table2时,它只会将user_table1的输出加倍,而不会显示第二个表中的用户 SELECT user_table1.age, user_table1.name, user_table1.lname, jobs.position, jobs.wage, employers.name employers.phone from u

嗨,我有用户_表1和用户_表2,我还有表格作业和雇主

当我从user_table1中获取用户并为他们获取工作和雇主信息时,我的请求就会起作用,但当我加入user table2时,它只会将user_table1的输出加倍,而不会显示第二个表中的用户

SELECT user_table1.age, user_table1.name,  user_table1.lname, jobs.position, jobs.wage, employers.name employers.phone 
from user_table1 
LEFT JOIN jobs ON jobs.position_id = user_table1.position_id
LEFT JOIN employers ON employers.position_id = jobs.position_id 
WHERE user_table1.age < 30
ORDER BY user_table1.age ASC
现在我也试着补充一下

SELECT user_table1.age, user_table1.name,  user_table1.lname, jobs.position, jobs.wage, employers.name employers.phone 
from user_table1 
LEFT JOIN jobs ON jobs.position_id = user_table1.position_id
LEFT JOIN employers ON employers.position_id = jobs.position_id 
LEFT JOIN user_table2 ON jobs.position = user_table2.position
WHERE user_table1.age < 30
user_table2.status = 4
ORDER BY user_table1.age ASC

换句话说,我需要检查user_table2.status=4的位置,然后将此记录与年龄小于30岁的user_table1中的所有记录合并,然后从jobs和employers中提取此记录的字段。

尝试合并两个表。您需要在联合体之外指定您的ORDERBY子句。UNION ALL允许重复。如果您不想重复,请删除ALL并仅使用UNION


我不清楚您对user_table1和user_table2的条件,即是否两者都应获得30岁过滤器,以及table2是否应是唯一具有状态4过滤器的。根据需要修改。

看起来不错,但这不是我通常写请求的方式。我想我以前有过这个问题,后来解决了,但现在我找不到了,我的原始查询有没有更简单的方法让它工作?@Johnds:如果我能解释一下你的问题,请告诉我是否正确。从两个具有不同过滤条件的表中获取记录,并将所有结果放入一个resultset。这是对你问题的正确描述吗?@Johnds:你再简单不过了。
SELECT * FROM 
(
    SELECT u.age, u.name,  u.lname, jobs.position, jobs.wage, employers.name employers.phone 
    from user_table1 as u
    LEFT JOIN jobs ON jobs.position_id = u.position_id
    LEFT JOIN employers ON employers.position_id = jobs.position_id 
    WHERE u.age < 30

    UNION ALL 

    SELECT u.age, user_table1.name,  user_table1.lname, jobs.position, jobs.wage, employers.name employers.phone 
    from user_table2 u  
    LEFT JOIN jobs ON jobs.position_id = u.position_id
    LEFT JOIN employers ON employers.position_id = jobs.position_id 
    WHERE u.age < 30
    AND u.status = 4
) AS UU
ORDER BY  UU.Age ASC