如何选择其他查询中不存在的数据

时间:2019-08-26 15:29:59

标签: mysql sql

我正在尝试从表数据中进行选择,但我希望结果不存在于此选择中。

(SELECT * FROM data WHERE category = 'A' ORDER BY RAND() LIMIT 4)
UNION ALL
(SELECT * FROM data WHERE category = 'B' ORDER BY RAND() LIMIT 4)` 

因此,没有行被选中为两倍。
sample data摆弄。

2 个答案:

答案 0 :(得分:0)

不存在:

SELECT * FROM table1 t1
WHERE NOT EXISTS (
  SELECT 1 FROM (
    (SELECT * FROM table1 WHERE category = 'A' ORDER BY RAND() LIMIT 4)
    UNION ALL
    (SELECT * FROM table1 WHERE category = 'B' ORDER BY RAND() LIMIT 4)
  ) t 
  WHERE t.id = t1.id AND t.category = t1.category  
)

请参见demo

答案 1 :(得分:0)

SELECT * FROM table1 where id not in ( 
  select id from ( 
    (SELECT * FROM table1 WHERE table1.category = 'A' ORDER BY RAND() LIMIT 4)     
    UNION ALL 
    (SELECT * FROM table1 WHERE table1.category = 'B' ORDER BY RAND() LIMIT 4)
  )
as t)