MYSQL在连接中获取其他表数据

发布于 2024-09-07 16:14:54 字数 603 浏览 2 评论 0原文

我当前正在运行此 SQL

SELECT jm_recipe.name, jm_recipe.slug
FROM jm_recipe
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"

这会返回所需的结果,除了我还需要返回我正在查找的菜谱所在的类别的名称,为此,我尝试将该字段添加到我的 SELECT< /code> 语句并将表添加到 FROM 子句中,

SELECT jm_recipe.name, jm_recipe.slug, jm_category_name
FROM jm_recipe, jm_category
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"

但是这只是返回没有结果,我做错了什么?

I am currently running this SQL

SELECT jm_recipe.name, jm_recipe.slug
FROM jm_recipe
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"

This returns the desired results except that I also need to return the name of the category that the recipe I am looking for is in, to do this I tried to add the field in to my SELECT statement and also add the table into the FROM clause,

SELECT jm_recipe.name, jm_recipe.slug, jm_category_name
FROM jm_recipe, jm_category
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"

However this just returns no results, what am i doing wrong?

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

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

发布评论

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

评论(1

非要怀念 2024-09-14 16:14:54

您需要连接两个表:

SELECT jm_recipe.name, jm_recipe.slug, jm.category_name
FROM jm_recipe 
    INNER JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
    INNER JOIN jm_category ON jm_recipe.recipe_id = jm_category.recipe_id
WHERE jm_category_recipe.category_id = $cat

我也将连接更改为内部连接。如果您有 NULL 并希望它们出现在结果中,您可能希望将它们都设为 LEFT 连接。

此外,只需复制 $catSQL 注入的攻击代码>.

这是一些 PHP 特定信息 (我假设您正在使用 PHP。)

You need to join both tables:

SELECT jm_recipe.name, jm_recipe.slug, jm.category_name
FROM jm_recipe 
    INNER JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
    INNER JOIN jm_category ON jm_recipe.recipe_id = jm_category.recipe_id
WHERE jm_category_recipe.category_id = $cat

I've changed the joins to inner joins as well. You might want to make them both LEFT joins if you have NULLs and want them in the result.

Also, you're vulnerable to SQL Injection by simply copying over $cat.

Here's some PHP specific info for you (I'm assuming you're using PHP.)

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