我正在开发一个产品系统,其中的产品可以包含在集合中。
在产品页面中,我显示所有产品,但如果某些产品位于集合中,我只需要显示集合名称,而不是产品本身。我的意思是,隐藏集合中的产品并显示该集合一次,同时还显示其他产品(不包含集合)。
表 1:colecciones(西类牙语“集合”)- 我存储集合的 ID 和名称的位置。
CREATE TABLE `colecciones` (
`id` INT(255) NOT NULL AUTO_INCREMENT ,
`nombre` VARCHAR(100) NOT NULL ,
PRIMARY KEY (`id`)
);
INSERT INTO `colecciones`
(`nombre`)
VALUES
('dulce'),('salado'),('agrio')
;
http://sqlfiddle.com/#!9/8534e/1/0
表 2:productos(“产品”)- 我存储产品的位置,如果它位于集合中,则存储集合 ID(“coleccion”列)。如果不是,则值为 0。
CREATE TABLE `productos` (
`id` INT(255) NOT NULL AUTO_INCREMENT ,
`nombre` VARCHAR(100) NOT NULL ,
`coleccion` INT(255) NOT NULL ,
PRIMARY KEY (`id`)
);
INSERT INTO `productos`
(`nombre`, `coleccion`)
VALUES
('manzana',1),('salmon',2),('sandia',0),('sopa',3),('pera',1),('agua',0)
;
http://sqlfiddle.com/#!9/6aef2/1/0
在示例中,名称为“manzana”(苹果)的产品是“dulce”(甜)系列的一部分,而产品“agua”(水)不属于任何系列。
我期望展示的是:
<h1>My products</h1>
dulce /* (ID 1 table `colecciones`) because I have products with "coleccion = 1" */
salado /* (ID 2 table `colecciones`) because I have products with "coleccion = 2" */
sandia /* the product itself, not collection */
agrio /* (ID 3 table `colecciones`) because I have products with "coleccion = 3" */
agua /* the product itself, not collection */
我被这个问题困住了。如何用PHP以这种方式显示数据?
我需要像productos.id DESC
这样的订单,我通过在末尾添加来完成:
ORDER BY c.`id` DESC
最佳答案
我认为聚合可以满足您的需求:
select (case when c.name is not null then c.name else p.name end) as name
from productos p left join
colecciones c
on p.coleccion = c.id
group by name, (c.name is not null);
group by
中的第二个条件只是确保当产品和 coleccion 具有相同名称时您会获得两行。
我也认为这适合您的目的:
select p.name from productos where coleccion = 0
union all
select c.name from colecciones;
您似乎想要不在集合中的所有产品加上集合名称(这就是此查询的作用)。
编辑:
我不确定你想要哪个 ID,但你可以这样做:
select p.name, p.id from productos where coleccion = 0
union all
select c.name, c.id from colecciones
order by id desc;
关于php - 展示产品或系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39400541/