我有一张桌子'产品'
id | title | color_id (fk) | type_id (fk) | price_range_id (fk)
我执行选择查询:
SELECT * FROM products where id = 1
我需要从同一张表中获取相关产品。我该怎么做呢?因此,我需要选择ID为1的行,然后选择10个具有相同colour_id
,type_id
和price_range_id
的其他产品。
此外,如果未选择10个相关产品,我需要随机选择余数,但不得包含已选择的行。
我没想到有人在这里做所有的工作,只是有人能指出我正确的方向从哪里开始这个问题?
答案 0 :(得分:0)
如果我理解你的问题,你应该创建这样的存储过程:
CREATE PROCEDURE sp_select(IN inId INT)
BEGIN
SET @numSelected := (SELECT COUNT(*) FROM t1
WHERE color_id = (SELECT color_id FROM t1 WHERE id = inId)
AND type_id = (SELECT type_id FROM t1 WHERE id = inId)
AND price_range_id = (SELECT price_range_id FROM t1 WHERE id = inId)
AND id != inId
LIMIT 10);
SET @numRemaind := (10 - @numSelected);
PREPARE statement FROM 'SELECT * FROM t1 WHERE id = ?
UNION ALL
SELECT * FROM (SELECT * FROM t1
WHERE color_id = (SELECT color_id FROM t1 WHERE id = ?)
AND type_id = (SELECT type_id FROM t1 WHERE id = ?)
AND price_range_id = (SELECT price_range_id FROM t1 WHERE id = ?)
AND id != ?
LIMIT 10) t
UNION ALL
SELECT * FROM (SELECT * FROM t1
WHERE id != ? AND
id NOT IN (SELECT id FROM t1
WHERE color_id = (SELECT color_id FROM t1 WHERE id = ?)
AND type_id = (SELECT type_id FROM t1 WHERE id = ?)
AND price_range_id = (SELECT price_range_id FROM t1 WHERE id = ?)
AND id != ?)
ORDER BY RAND()
LIMIT ?) tx';
SET @p1 = inId;
SET @p2 = @numRemaind;
EXECUTE statement USING @p1, @p1, @p1, @p1, @p1, @p1, @p1, @p1, @p1, @p1, @p2;
END//
以下是SQL Fiddle,了解它是如何运作的。在表的第一行中,将选择具有相同color_id,type_id和price_range id的行,如果没有要添加的10行,则将添加在先前步骤中未选择的随机行...
GL!