mysql联合问题

标签 mysql

mysql> select job_desc_title from postings where id=194582;
+-----------------------------+
| job_desc_title              |
+-----------------------------+
| Speech/Language Pathologist |
+-----------------------------+
1 row in set (0.00 sec)
mysql> select email_address,first_name,last_name,home_phone_area,home_phone_num from accounts
->  left join profiles on profiles.account_id=accounts.id  
->  where accounts.id=5;
+--------------------+------------+-----------+-----------------+----------------+
| email_address      | first_name | last_name | home_phone_area | home_phone_num |
+--------------------+------------+-----------+-----------------+----------------+
| newhjh@hotmail.com | Jianhua    | He        | 425             | 3584396        |
+--------------------+------------+-----------+-----------------+----------------+
1 row in set (0.00 sec)

I need to union the above 2 queries,but my trial failed:

mysql> select job_desc_title from postings where id=194582
->                           union all
->                     select email_address,first_name,last_name,home_phone_area,home_phone_num from accounts
->                      left join profiles on profiles.account_id=accounts.id
->                      where accounts.id=5;

ERROR 1222 (21000): The used SELECT statements have a different number of columns

完成这项工作的正确版本是什么?

最佳答案

您从第一个中选择 job_desc_title,然后从第二个中选择电子邮件地址、名字、姓氏等。这不是工会。

您要做的是加入,我建议您仔细阅读这些内容。联合获取两个查询的结果并将它们垂直组合。联接获取两个表的结果并将它们水平组合。联合添加行,连接添加列。您要做的是添加一列 (job_desc_title),而不是行。合并行(即并集)需要相同的列。

我还认为您应该使用内部联接时却使用了左联接。

select 
    a.email_address,
    a.first_name,
    a.last_name,
    a.home_phone_area,
    a.home_phone_num,
    post.job_desc_title
from 
    accounts a
    inner join profiles p on 
        a.id=p.account_id
    inner join postings post on
        --I have no idea what the relationship is here, so I'm guessing
        p.posting_id = post.id
where 
    a.id=5

希望这会让您接近正确的轨道。

关于mysql联合问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/912285/

相关文章:

mysql替换字符串的一部分

mysql - 多次更新 - 可能的错误

mysql - php mysql 按 yyyy-mm-dd 格式的日期进行分组

mysql - 如何使用数组创建 MySQL 查询?

mysql - 在 MySQL 中存储出生日期

php - 在mysql中使用pdo获取多个插入的第一个插入ID

php - 在一个字段中存储多个值

mysql - UPDATE 比等效的 SELECT 影响更少的行

Mysql将子查询转换为依赖子查询

mysql - 根据条件进行内连接或在哪里使用?