【问题标题】:Select from table1 on condition specific elements from table1 don't exist in table2从表 1 中选择表 1 中的条件特定元素在表 2 中不存在
【发布时间】:2016-01-13 17:42:45
【问题描述】:

words 包含列:word_id word

我的查询打印为:

SELECT word FROM words WHERE condition1 AND condition2 ORDER BY RAND() LIMIT 5000

solved 包含列:user_id word_id

我想获取 5000 个随机行,条件是在表 solved 中找不到任何一行 user = username

到目前为止我已经尝试过:

SELECT word FROM words w 
WHERE not exists 
(select 1 from solved s where s.word_id = w.word_id 
AND s.user_id = 'username') 
AND condition1 AND condition2 ORDER BY RAND() LIMIT 5000

【问题讨论】:

    标签: mysql conditional-statements where


    【解决方案1】:

    使用LEFT JOIN 表示:

    SELECT word 
    FROM words w 
    left join solved s on s.word_id = w.word_id AND s.user_id = 'username'
    WHERE w.word_id is null
    AND condition1 AND condition2 
    ORDER BY RAND() LIMIT 5000
    

    【讨论】:

    • 你说你想要第一个表中的记录,而第二个表中没有相应的记录。那是因为null
    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多