php - 检查引用另一个表的表中的特定行?

标签 php mysql sql-server

我知道这个问题对我的要求没有任何意义,但我的意思是......为了更清楚地说明,我将在示例中说明我的问题:

我有一个 userpost 表,其中包含来自不同用户的帖子。

userpost 表:

 +---------+--------+--------------+
 |  postId | userId | postMessage  |
 +---------+--------+--------------+
 |       1 |      3 | someText     |
 |       2 |      5 | someText     |
 |       3 |      2 | sometext     |
 |       5 |      6 | someText     |
 +---------+--------+--------------+

(!记住 userId 被引用到 users 表)

我有另一个名为 favorites 的表,其中 postId 是从 userpost 表中引用的:

收藏夹表:

+---------+--------+
|  postId | userId |
+---------+--------+
|       1 |      5 |  
|       3 |      2 |  
+---------+--------+

我想要的是从 userpost 获取所有数据并检查某个用户帖子是否已被 (WHERE userId = 5) 收藏

我试过使用这个查询,但这不是我想要的!

    SELECT *,
    (SELECT EXISTS( SELECT * FROM `favorites` INNER JOIN `userpost` on 
    favourites.postId = userpost.postId WHERE favorites.postId = 1 
    AND   favorites.userId = 5)) AS isFavourited FROM userpost;

这是以下查询的结果:

+---------+--------+-------------+--------------+
|  postId | userId | postMessage | isFavourited |
+---------+--------+-------------+--------------+
|       1 |      3 | someText    |            1 |  
|       2 |      5 | someText    |            1 | 
|       3 |      2 | someText    |            1 |  
|       5 |      3 | someText    |            1 | 
+---------+--------+-------------+--------------+

我知道我在使用以下查询时犯了错误:

(WHERE favorites.postId = 1 AND favorites.userId = 5)

确实返回 true。

我会给你一个我想要的的例子:

假设 (userId = 5) 想要获取所有 userpost,我们必须得到以下结果:

+---------+--------+-------------+--------------+
|  postId | userId | postMessage | isFavourited |
+---------+--------+-------------+--------------+
|       1 |      3 | someText    |            1 |  
|       2 |      5 | someText    |            0 | 
|       3 |      2 | someText    |            0 |  
|       5 |      3 | someText    |            0 | 
+---------+--------+-------------+--------------+

最佳答案

尝试:

SELECT *, 
    postId IN 
        (SELECT postId FROM favourites WHERE userId = 5) 
    AS isFavourited
FROM userPost

您的查询检查是否存在用户 5 收藏夹发布 1 的行;不是用户 5 喜欢在返回的那一行中选择的帖子。

关于php - 检查引用另一个表的表中的特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273233/

相关文章:

sql-server - ColdFusion 10 serializeJSON 将是/否字符串转换为 bool 值 - 如何阻止它?

sql - 非 NULL 值的 ISNULL/COALESCE 对应物

java - 更改 SQL Server DB 中列的数据类型时出错 - Java

php - Elasticsearch:如何在聚合中使用多重过滤和计算?

mysql - 哪个数据库是面向性能的,MySQL 还是 MariaDB?

php - 订购 if/else if 语句的最快/正确方法

php - Yii2 - 在 GridView 中按一对多对一关系排序和过滤

mysql - 将MySQL数据库传输到远程服务器

iis - 无法保存 php.ini

php - Twitter typeahead 与 mysql 源代码