如何从具有这些条件的表中进行选择?

时间:2017-03-03 07:47:51

标签: mysql

该表有以下4列:

id       int(11) not null  primary key,
name     varchar   not null ,
status   tinyint(1)  not null,
created  datetime not null

现在,我想找出条件结果行:

  1. 状态为0;
  2. 将结果行预设为A,如果表格可以选择具有相同name的行名称B且created是同一天且status为1,则A除外。
  3. 有人可以用没有嵌套选择的sql选择结果,非常感谢!

4 个答案:

答案 0 :(得分:1)

听起来像反连接模式符合要求。此模式需要两个对表的引用,但只需要一个SELECT关键字。举个例子:

 SELECT t.id
      , t.name
      , t.status
      , t.created 
   FROM the_table t
     -- anti-join exclude matching rows
   LEFT
   JOIN the_table d
     ON d.name = t.name
    AND d.status = 1
    AND d.created >= DATE(t.created)
    AND d.created <  DATE(t.created) + INTERVAL 1 DAY
  WHERE d.name IS NOT NULL 
    AND t.status = 0

技巧是外连接,返回t中的所有行,以及来自d的匹配行,以及WHERE子句中排除所有行的条件有匹配。仅保留t中没有来自d的匹配行的行。

答案 1 :(得分:0)

name不在具有第二个条件的行中:

SELECT * FROM tablename as o
WHERE o.status = 0
  AND o.name NOT IN
   (
    SELECT `name` FROM tablename as i
    WHERE i.status = 1
      AND i.created
          BETWEEN DATE(t.created)
              AND DATE(t.created) + INTERVAL 1 DAY
   )

答案 2 :(得分:0)

试试这个:

 select a.id,a.name,a.created,a.status from
(select b.id,a.name,b.created,b.status from 
(select count(name) as cnt, name from tbl_sample as a GROUP BY name) as a
LEFT JOIN
(select * from  tbl_sample) as b
on   a.`name` = b.`name`  where cnt>1 and STATUS = 0) as a

LEFT JOIN


(select b.id,b.name,b.created,b.status from 
(select count(created) as cnt, created from tbl_sample as a GROUP BY created) as a
LEFT JOIN
(select * from  tbl_sample) as b
on   a.`created` = b.`created`  where cnt>1 and STATUS = 0) as b
on a.id = b.id

答案 3 :(得分:0)

SELECT a.id, a.name, a.status, a.created 
FROM userTable as a 
LEFT JOIN userTable as b 
ON a.name = b.name 
AND b.status = 1 
AND b.created BETWEEN DATE(a.created) AND DATE(DATE_ADD(a.created, INTERVAL 1 day))  
WHERE a.status = 0 
AND a.name IS NULL;

感谢@ spencer7597的回答,我找到了结果。