我正在尝试选择一个用户尚未投票的T恤(来自另一张表“投票”)
“提交”是带有tshirts的表格
“投票”是持有投票的表格
“投票”结构是:ID,TEE,USER(其中votes.tee == submissions.id)
这是我正在尝试的mysql语句:
SELECT
submissions.name,
submissions.id,
submissions.uploader,
submissions.image_vote
FROM
submissions,votes
WHERE
submissions.date_voted IS NOT NULL AND
submissions.id NOT IN (SELECT tee FROM votes WHERE tee=submissions.id AND user='3')
LIMIT 1
根据我的理解,我不能使用“tee = submissions.id”,因为它来自此子查询之外的查询。那么如何将子查询传递给我正在检查的T恤的ID?
谢谢。
答案 0 :(得分:3)
子选择从来就不是mysql中特别闪亮的区域。相反,使用外部联接:
SELECT
submissions.name,
submissions.id,
submissions.uploader,
submissions.image_vote
FROM
submissions LEFT OUTER JOIN votes ON(votes.tee=submissions.id)
WHERE
submissions.date_voted IS NOT NULL AND votes.tee IS NULL
LIMIT 1
左外连接确保每个适用的submissions
记录在结果中至少生成一条记录 - 如果votes
中不存在相应的记录,则votes
字段在连接记录中设置为NULL,因此AND votes.whatever IS NULL
子句选择在votes
中不存在相应记录的连接记录。
答案 1 :(得分:1)
你试过这个:
SELECT
submissions.name,
submissions.id,
submissions.uploader,
submissions.image_vote
FROM
submissions,votes
WHERE
submissions.date_voted IS NOT NULL AND
submissions.id NOT IN (SELECT tee FROM votes WHERE user='3')
LIMIT 1
也许不是最有效的,但尽可能接近你的想法。