[英]Mysql limit results based on value from column
I'm trying to limit the number of results of a query based on another table column. 我试图限制基于另一个表列的查询结果的数量。 For example, I have a table for products and a config table, like this: 例如,我有一个产品表和一个配置表,如下所示:
tb_product
id | active | name | value | ...
tb_config
max_product | ...
What I'd like to do is something like this 我想做的是这样的
SELECT
a.name, a.value
FROM
tb_product a,
tb_config b
WHERE a.active = 1
LIMIT b.max_product
But I'm getting errors like #1327 - Undeclared variable: b
. 但是我遇到了类似#1327 - Undeclared variable: b
错误#1327 - Undeclared variable: b
。 Is there a way to achieve this result? 有没有办法达到这个结果?
Because currently what I'm doing is doing another query to get just the max_product value and then use it as php variable to limit the results, like this: 因为当前我正在做的是另一个查询,只是获取max_product值,然后将其用作php变量以限制结果,例如:
$limit = "SELECT max_product FROM tb_config";
SELECT name, value FROM tb_product WHERE ativo = 1 LIMIT $limit
Maybe.... 也许....
SELECT a.name
, a.value
FROM tb_product a
CROSS JOIN (SELECT @Limit:=(SELECT max_product from tb_config))
WHERE a.active = 1
LIMIT @Limit
With help from @ENargit's answer in Variable LIMIT Clause in MySQL , you can do it using a row count variable. 在MySQL的LIMIT LIMIT子句中 ,借助@ENargit的答案,您可以使用行计数变量来完成此操作。
Assuming the following schema: 假设以下架构:
CREATE TABLE
tb_product
(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(10),
`value` VARCHAR(10)
);
INSERT INTO
`tb_product`
(`name`, `value`)
VALUES
('Name1','Value1'),
('Name2','Value2'),
('Name3','Value3'),
('Name4','Value4'),
('Name5','Value5'),
('Name6','Value6'),
('Name7','Value7'),
('Name8','Value8'),
('Name9','Value9'),
('Name10','Value10');
CREATE TABLE
`tbl_config`
(
id INT PRIMARY KEY AUTO_INCREMENT,
`type` VARCHAR(10),
`value` INT
);
INSERT INTO
`tbl_config`
(`type`,`value`)
VALUES
('something',10),
('maxrows',7);
You can reference the config table with a subquery: 您可以使用子查询引用配置表:
SELECT * FROM (
SELECT
tb_product.*,
@rownum := @rownum + 1 AS RowNum
FROM tb_product,
(SELECT @rownum := 0) AS CounterTbl
) AS DataTbl
WHERE
RowNum <= (
SELECT
`value`
FROM
`tbl_config`
WHERE
`type` = 'maxrows'
);
Gives you the first 7 rows (according to the config value). 给您前7行(根据config值)。 You can obviously extend this to do sorting etc. 您显然可以将其扩展为进行排序等。
SQLFiddle: http://www.sqlfiddle.com/#!9/f789e4/2 SQLFiddle: http ://www.sqlfiddle.com/#!9 / f789e4 /2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.