gpt4 book ai didi

mysql - 连接两个 MySQL 表,但有附加条件?

转载 作者:行者123 更新时间:2023-12-01 00:27:54 25 4
gpt4 key购买 nike

我有两个表:

产品:

+-------------------------------------------------+
| id | name | category | price |
+-------------------------------------- ----------+
| 1 | item1 | 1 | 0.99 |
| 2 | item2 | 2 | 1.99 |
| 3 | item3 | 3 | 2.95 |
| 4 | item4 | 4 | 2.50 |
+-------------------------------------------------+

图片:

+--------------------------------------------------+
| id | file_name | p_id | priority |
+-------------------------------------- -----------+
| 1 | image1 | 1 | 0 |
| 2 | image2 | 1 | 1 |
| 3 | image3 | 2 | 2 |
| 4 | image4 | 3 | 2 |
| 5 | image5 | 3 | 3 |
| 11 | image6 | 3 | 5 |
| 16 | image7 | 4 | 1 |
| 19 | image8 | 4 | 7 |
+--------------------------------------------------+

我需要获取所有产品信息,以及产品图片的文件名。请注意,一个产品可以有多个图像;我想要具有最低 优先级的那个。此外,我只想要特定类别产品的结果。

所以,假设我需要类别 {1,2,3} 中产品的信息,那么在查询运行后结果应该返回:

+-----------------------------------------------------------------+
| id | name | category | price | file_name |
+-------------------------------------- ----------+---------------+
| 1 | item1 | 1 | 0.99 | image1 |
| 2 | item2 | 2 | 1.99 | image3 |
| 3 | item3 | 3 | 2.95 | image4 |
+-------------------------------------------------+---------------+

我试过写几个不同的连接语句,但没有一个起作用;不足为奇,因为在 SQL 方面我完全是个新手。

如有任何帮助,我们将不胜感激!

最佳答案

我将添加一个分步教程,首先要正确连接,然后添加一些条件来过滤类别,最后分组并将 having 子句与子选择一起使用。您将需要使用最后一次选择在你的代码中。我还在 mysql 实例上测试了它并且它有效。我正在使用 group by 以防你需要一些其他复杂的东西。有个例子很好。语法是 ansii sql,它应该适用于所有数据库,而不仅仅是 mysql

-- get everything by joining
select p.*, i.file_name
from products p
join image i on (p.id = i.p_id)



/* get everything by joining
* + filter by category
*/
select p.*, i.file_name
from products p
join image i on (p.id = i.p_id)
where p.category in (1,2,3)


/* get everything by joining
* + filter by category
* + image is the one with the lowest priority
* note: selecting the priority is not necessary
* but it's good for demonstration purposes
*/
select p.*, i.file_name, i.priority
from products p
join image i on (p.id = i.p_id)
where p.category in (1,2,3)
group by p.id
having i.priority = (select min(priority) from image where p_id = p.id)

关于mysql - 连接两个 MySQL 表,但有附加条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10666965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com