[英]Selecting a mysql row from one table based on select statement in another
I am trying to select a tshirts which the user has not voted on yet (from another table "votes") 我正在尝试选择一个用户尚未投票的T恤(来自另一个表“投票”)
"submissions" is the table with the tshirts “提交”是带有T恤的表格
"votes" is the table that holds votes “投票”是持有选票的表格
"votes" structure is: ID, TEE, USER (where votes.tee == submissions.id) “投票”结构是:ID,TEE,USER(其中votes.tee == submissions.id)
This is the mysql statement I am trying: 这是我正在尝试的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
Now from what I understand I cannot use "tee=submissions.id" because it is from a query outside of this sub query. 根据我的理解,我不能使用“tee = submissions.id”,因为它来自此子查询之外的查询。 So how can I pass the sub query the ID of the tshirt I am checking?
那么如何将子查询传递给我正在检查的T恤的ID?
Thank you. 谢谢。
sub-selects have never been a particulary shiny area in mysql. 子选择从来都不是mysql中特别闪亮的区域。 Rather, use an outer join:
而是使用外连接:
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
the left outer join makes sure that at least one record is produced in the result per applicable record of submissions
-- if no corresponding record exists in votes
, then the votes
fields in the joined record are set to NULL, so the AND votes.whatever IS NULL
subclause picks out the joined records where no corresponding record exists in votes
. 左外连接确保在每个适用的
submissions
记录的结果中至少生成一条记录 - 如果votes
不存在相应的记录,则连接记录中的votes
字段设置为NULL,因此AND votes.whatever IS NULL
子句选择连接记录,其中在votes
中不存在相应的记录。
Did you try this: 你试过这个:
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
Maybe not the most efficient, but as close to your idea as possible. 也许不是最有效的,但尽可能接近你的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.