sql - mysql选择数据

标签 sql mysql

我有两个表,productsproduct_tags

产品表;

product_id int
name varchar
description text
price decimal(12,2)
status enum
sale int
hit int
date_add datatime
date_update datetime

product_tags 表;

tag_id int
product_id int
tag varchar

其中 product_tags 表与 products 具有一对多关系,例如:

tag_id | product_id | tag
1       1             tag1
2       1             tag2
3       1             tag3

我想从单个查询中提取数据。 (产品和产品标签)。

最佳答案

使用这样的东西:

SELECT *
  FROM products p
 INNER JOIN product_tags pt
    ON (p.product_id = pt.product_id)

如果您想获取所有产品,无论它们是否有标签,请使用 OUTER JOIN。

SELECT *
  FROM products p
  LEFT OUTER JOIN product_tags pt
    ON (p.product_id = pt.product_id)

如果您尝试将每个产品的所有标签合并到一个逗号分隔的列表中,那么类似这样的操作可能会在 mysql 中起作用:

SELECT p.product_id, GROUP_CONCAT(pt.tag SEPARATOR ',')
  FROM products p
  LEFT OUTER JOIN product_tags pt
    ON (p.product_id = pt.product_id)
 GROUP BY p.product_id;

有关 GROUP_CONCAT 的更多文档,请参阅 MySQL Reference Manual

关于sql - mysql选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3271312/

相关文章:

sql - "ORA-00922: missing or invalid option"创建表时

php - 计算 true bool 与 false 的百分比

php - 用户在表单中插入日期

php文件上传到数据库

sql - 不使用关系数据库的充分理由?

sql - t-sql 返回错误代码与 RaiseError

sql - 甲骨文 PL/SQL : How to pretty print a large number

php - 使用 PDO 左连接

python - 使用 python 脚本推断 excel 文件中的数据

mysql - 插入 - 在重复的键上