Php Mysql根据一个表的ID从两个表中选择数据

Php Mysql根据一个表的ID从两个表中选择数据,php,mysql,sql,Php,Mysql,Sql,我有两张桌子。我需要根据另一个表的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|

我有两张桌子。我需要根据另一个表的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将来自
第一个\u表
用户ID
列。

MAX()
案例
帮助您获得结果

试试这个:

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

您可以对这两个表进行内部联接,并且由于您希望在
user\u id
级别查看输出,因此可以基于将转换为列的
meta\u键
,使用MAX(或者甚至其他函数,因为这些都是文本值)聚合其他字段

SELECT A.USER_ID,
MAX(CASE WHEN B.META_KEY = 'FIRST_NAME' THEN B.META_VALUE END) AS FIRST_NAME,
MAX(CASE WHEN B.META_KEY = 'LAST_NAME' THEN B.META_VALUE END) AS LAST_NAME,
MAX(CASE WHEN B.META_KEY = 'EMAIL' THEN B.META_VALUE END) AS EMAIL
FROM
FIRST_TABLE A
INNER JOIN
SECOND_TABLE B
ON A.USER_ID = B.POST_ID
GROUP BY A.USER_ID;

您可以不使用内部联接进行尝试

   function userdata($id){
        $SQL = "SELECT user_id FROM first_table where user_id= :id;
        $q = $this->DBcon->prepare($SQL);
        $q->execute(array(':id' => $id));
        $data = $q->fetch(PDO::FETCH_ASSOC);
        $postid = $data[post_id]
        $sql2 = "SELECT post_id, first_name, last_name, email FROM second_table Where post_id = $postid";
        $q = $this->DBcon->prepare($SQL2);
        $q->execute();
        $data = $q->fetch(PDO::FETCH_ASSOC);
    }
如果您需要在查询的最后一个语句中使用where子句
如果user_id=4

则显示的演示表是错误的数据存储方式。正确的数据存储方式是将用户详细信息分别存储在用户表和post表中。然后将用户表的主键添加为post表的外键。
然后您可以执行查询以获得上述结果。

试试我的答案,希望能有所帮助
SELECT first_table.user_id,second_table.post_id,second_table.meta_key  ,second_table.meta_value first_table LEFT JOIN second_table ON first_table.user_id=second_table.post_id;