sql - 使用 SQL 选择之前未比较过的两行

标签 sql mysql comparison

我有一个数据库,用户可以在其中看到两个项目并选择两者中较好的一个。我只想向用户展示他们尚未进行的比较。我有两个表:

项目表

+--------+---------+
| itemId |  name   |
+--------+---------+
|   1    | Dog     |
|   2    | Cat     |
|   3    | Fish    |
|   4    | Rat     |
+--------+---------+

投票表

+--------+--------------+--------------+--------+
| voteId | betterItemId |  worseItemId | userId |
+--------+--------------+--------------+--------+
|    1   |       1      |       2      |    1   |
+--------+--------------+--------------+--------+
|    1   |       1      |       3      |    1   |
+--------+--------------+--------------+--------+

我需要一个 (My)SQL 查询,为我提供两个随机项目供用户比较,用户尚未相互比较。

最佳答案

select a.itemId, a.name, b.itemId otherItemId, b.name othername
from item a
inner join item b on a.itemId < b.itemId
where not exists (
  select * from vote v
  where ((v.betterItemId = a.itemId and v.worseItemId = b.itemId)
     or  (v.betterItemId = b.itemId and v.worseItemId = a.itemId))
    and v.userId = 1234)   # << enter the userId here
order by rand()
limit 1;
  • 首先生成所有的 a-b 组合,但使用 a.id<b.id以防止重复(例如 1-2 和 2-1)。
  • 接下来,对于 a-b 的每个组合,检查(在任何更好-更差或更差-更好的排列中)该项目是否已被 userId 投票(查询中的 1234 示例)
  • 使用 order by rand() 对所有结果进行随机排序
  • 使用limit 1只得到 1 行
  • 在选择中,显示两个项目的 ID 和名称

要将其显示为两个单独的行,应使用前端。但是要纯粹在 MySQL 中执行此操作,需要一个技巧。以下内容在撰写本文时未经测试。

select ItemId, name
from
(
    select a.itemId, a.name, @b := b.itemId
    from item a
    inner join item b on a.itemId < b.itemId
    where not exists (
      select * from vote v
      where ((v.betterItemId = a.itemId and v.worseItemId = b.itemId)
         or  (v.betterItemId = b.itemId and v.worseItemId = a.itemId))
        and v.userId = 1234)   # << enter the userId here
    order by rand()
    limit 1
) c
union all
select itemId, name
from item d on d.itemId = @b

关于sql - 使用 SQL 选择之前未比较过的两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4804138/

相关文章:

c++ - 双重比较

sql - 将参数数组传递给存储过程

php - 使用 PHP SQL 在数据库中查找特定值

php - “简单”mysql 查询需要 30 秒加载

mysql - 使用 ColdFusion 将日期和时间插入 MySQL

objective-c - Objective-C : Comparison issue between numbers

sql - ORA-00933: SQL 命令未正确结束

mysql - 我需要删除列中所有前导 0

sql - 从同一个表的组中减去值

c++ - 如何以 std::weak_ptr 作为键比较两个 std::map?