mysql - 从 MySQL 选择唯一行

标签 mysql sql

希望你们能帮忙,因为这已经困扰我几天了。我正在尝试从表中获取唯一行的总数。例如,表中的数据如下所示;

 user_1 | user_2 | date_added          | date_removed        
--------|--------|---------------------|---------------------
 1      | 2      | 2016-09-20 15:51:45 | 2016-09-24 09:15:32 
 1      | 3      | 2016-09-21 10:16:03 | 2016-09-29 00:46:44
 6      | 1      | 2016-09-23 05:48:59 | 0000-00-00 00:00:00
 1      | 3      | 2016-09-30 09:57:16 | 0000-00-00 00:00:00

我想要找到的是 user_id 出现的总行数(user_1 列或 user_2 列),其中也只有一个条目对于该用户配对(用户配对将始终位于同一列中),并且 date_removed = 0000-00-00 00:00:00

因此,如果我在上表中搜索 user_id“1”,总数将为“1”。 (只有第三行符合搜索条件); 其中搜索 user_id“2”将等于“0”; user_id 的“3”等于“0”; “6”的 user_id 等于“1”;

希望这是有道理的。任何帮助或指示将不胜感激。

---- 编辑 ----

这是我到目前为止的查询,我尝试了几种方法,包括连接等,但这让我到目前为止最接近,而且我确信它不是最干净的方法!

SELECT COUNT(*) AS `count` 
FROM `table` 
WHERE (`user_1` = '1' OR `user_2` = '1') 
GROUP BY `user_1`, `user_2` 
HAVING `count` < '2' AND MAX(`date_removed`) < '0000-00-00 00:00:01'

但是,当表中出现更多数据时,查询结果如下所示:

count
-----
1
1
1

我希望它显示的位置:

count
-----
3

最佳答案

实现这一目标的方法不止一种。 我正在发送一个选项,创建一个 View 以使其更容易,但如果您不想创建 View ,则可以在子查询中使用其代码。

  1. 创建一个 View 来合并 user1、user2 的所有可能组合

    create view result as
    select user1, user2, date_removed from test
    union all
    select user2, user1, date_removed from test
    
  2. 创建查询

    select r.user1, r.user2
    from result r
    where
        r.date_removed = '0000-00-00 00:00:00'
        and r.user2 not in (select r2.user2 
                            from result r2 
                            where r2.date_removed <> '0000-00-00 00:00:00')
    

希望能帮助你解决这个问题。

关于mysql - 从 MySQL 选择唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802255/

相关文章:

MySql Group_concat 多行

sql - 查找两个不同时间线的时间重叠

mysql - PostgreSQL 的 EXPLAIN ANALYZE 的 MySQL 等价物是什么

mysql - 部分查询的错误消息 :Either list of columns or a custom serializer should be specified

python - 如果我需要自动递增 ID 但想要检查另一个字段上的重复项,如何定义模型?

php - 使用单个复选框更改多行的复选框属性

java.sql.Connection 隔离级别

mysql - IN 内的 SQL 查询结果

php - 搜索没有撇号的词(有撇号的)

mysql - 具有多个参数的 IN() 函数