php - 如何连接两个mysql表

标签 php mysql

我有两个 mysql 表。即,

  1. db_post
  2. db_like

//db_post

id  ||  name  ||  username  ||  unique_key  ||  pub

1       Jit        jit11         unkey1         demo
2       Rah        rah11         unkey2         demo1
3       dee        dee11         unkey3         demo2

//类数据库

id  ||  post_id  ||  unique_key

1          2           unkey3

我的问题是,如何根据 db_post 表中的 unique_key 字段混合这两个表。

//输出应该如下所示。 (WHERE unique_key='unkey3')

id  ||  name  ||  unique_key  ||  pub

3       dee         unkey3        demo2
2       Rah         unkey3        demo1 -> Result from table db_like

最佳答案

我不明白为什么@tango给出的答案被接受了,查询没有给出想要的输出,它返回这个:

id  ||  name  ||  unique_key  ||  id
3       dee       unkey3          1

事实上,我看不出如何通过一次连接来连接这两个表来获得您在问题中所写的输出。

要么你加入使用 unique_key 列的表,像这样:

select db_post.id, db_post.name, db_post.unique_key, db_post.pub
from db_post
left join db_like on db_post.unique_key = db_like.unique_key
where db_post.unique_key = 'unkey3';

并且您获得了所需输出的第一行:

id  ||  name  ||  unique_key  ||  pub
3       dee       unkey3          demo2

要么使用 db_post.id = db_like.post_id 连接两个表:

select db_post.id, db_post.name, db_like.unique_key, db_post.pub
from db_post
left join db_like on db_post.id = db_like.post_id
where db_like.unique_key = 'unkey3';

并且您获得了所需输出的第二行:

id  ||  name  ||  unique_key  ||  pub
2       Rah       unkey3          demo1

要获得这两行,您必须使用union:

select db_post.id, db_post.name, db_post.unique_key, db_post.pub
from db_post
left join db_like on db_post.unique_key = db_like.unique_key
where db_post.unique_key = 'unkey3'
union
select db_post.id, db_post.name, db_like.unique_key, db_post.pub
from db_post
left join db_like on db_post.id = db_like.post_id
where db_like.unique_key = 'unkey3';

关于php - 如何连接两个mysql表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890245/

相关文章:

php - 获取结果并将它们用于另一个查询 mysql php

php - PJAX 不工作

php - 具有 2 个选定列的查询每行仅返回 1 列

php - 在不使用循环的情况下将字符串分解为关联数组?

javascript - 一种检测隐身浏览的方法?

php - 将值插入 mysql_query 中的新表

MYSQL if/else 子句

mysql - 无法计算出 MySQL 查询

php - PHP 中的长字符串加密和解密

mysql - 如何使用 mySQL 和 C# 缓冲多个数据库插入请求以便稍后延迟批量执行?