如何在连接 3 个表时进行搜索但排除其中之一的结果?

发布于 2024-12-01 20:49:17 字数 626 浏览 2 评论 0原文

我已经花了几个小时才得到一个特定的结果,但在网上没有找到任何答案 - 由于我根本不是 SQL 专家,所以我在这里问一个问题。

我有 3 个表:user (id, name...), cars (id< /code>、typecolorengine power...)和一个中间表来保存用户给汽车的所有分数: 分数iduser_idcar_idscore)。

我试图找到一个可以为某个特定用户返回的查询,即他尚未评分的所有汽车。我已经尝试过以下操作,但它返回 null:

$q=mysql_query("SELECT * FROM cars LEFT OUTER JOIN scores ON cars.id = scores.car_id WHERE scores.user_id != ('".$userId."')");

有人有线索吗?

I've been tying for hours now to get a particular result and haven't found any answer on the web - and as I'm not an SQL expert at all, I'm asking a question here.

I have 3 tables: user (id, name...), cars (id, type, color, engine power...) and an intermediary table to save all the scores users gave to the car: scores (id, user_id, car_id, score).

I'm trying to find a query that could return for one particular user, all the cars that he hasn't rated yet. I've tried the following but it returns null:

$q=mysql_query("SELECT * FROM cars LEFT OUTER JOIN scores ON cars.id = scores.car_id WHERE scores.user_id != ('".$userId."')");

Does someone have a clue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

世界等同你 2024-12-08 20:49:18

您可以使用您的代码进行少量修改:

SELECT * FROM cars 
LEFT OUTER JOIN scores ON cars.id = scores.car_id and scores.user_id=".$userId."
WHERE scores.id IS NULL

You can use your code with small modification:

SELECT * FROM cars 
LEFT OUTER JOIN scores ON cars.id = scores.car_id and scores.user_id=".$userId."
WHERE scores.id IS NULL
花心好男孩 2024-12-08 20:49:18
SELECT * FROM
car c
WHERE c.id NOT IN (
    SELECT s.car_id
    FROM score s, user u
    WHERE u.id = s.user_id
        AND u.id = ?
)
SELECT * FROM
car c
WHERE c.id NOT IN (
    SELECT s.car_id
    FROM score s, user u
    WHERE u.id = s.user_id
        AND u.id = ?
)
九命猫 2024-12-08 20:49:17
SELECT
  *
FROM
  cars
WHERE
  NOT EXISTS (SELECT 1 FROM scores WHERE car_id = cars.id AND user_id = ?)

其中 ? 是该特定用户的 ID。

此处,scores(car_id, user_id) 的复合索引很有用。

SELECT
  *
FROM
  cars
WHERE
  NOT EXISTS (SELECT 1 FROM scores WHERE car_id = cars.id AND user_id = ?)

where ? is the ID of that particular user.

A composite index in scores over (car_id, user_id) is useful here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文