php - Mysql根据一张表的ID从2张表中选择数据

标签 php mysql sql

我有两张 table 。我需要根据另一个表中的 ID 从一个表中选择数据。

表格是:

第一个表

user_id
4      
5      
6      

第二个表

post_id|meta_key  |meta_value   |
1      |email     |test@test.com|
1      |first_name|test         |
1      |last_name |hey          |
2      |email     |test@test.com|
2      |first_name|test         |
2      |last_name |hey          |
3      |email     |test@test.com|
3      |first_name|test         |
3      |last_name |hey          |
4      |email     |4th@test.com |
4      |first_name|4th fname    |
4      |last_name |4th          |
5      |email     |test@test.com|
5      |first_name|test         |
5      |last_name |hey          |
6      |email     |test@test.com|
6      |first_name|test         |
6      |last_name |hey          |

我需要的数据为:

post_id|first_name|last_name|email
4      |4th fname |4th      |4th@test.com

同样,我将获得 post_id 5,6 的数据。 ID 将来自 first_table user_id 列。

最佳答案

MAX()CASE 帮助您获得结果。

试试这个:

select post_id
    ,max(case when meta_key='first_name' then meta_value end)first_name
    ,max(case when meta_key='last_name ' then meta_value end)last_name 
    ,max(case when meta_key='email' then meta_value end)email
from second_table
where post_id in(select user_id from first_table) 
group by post_id

关于php - Mysql根据一张表的ID从2张表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48220161/

相关文章:

php - 在 PHP 中使用 HybridAuth 时如何更新用户状态?

php - 如何使用 codeigniter 编写此查询?

php - Laravel 5.1 创建链接到 user_id 的产品

php - 选择最接近变量的值

mysql - SQL查询用于查找每个部门的子部门数量

带有 MySQL 的 PHP 仅对表的第一行返回正确的结果

mysql - Rails/Mysql2/Lion [致命] 分配内存失败

mysql - 如何查看查询中的参数?

sql - 用同一表中另一列的数据填充列

php - 今天的 SQL 查询