所以我有一个包含3列的表格,其中包含我想要的数据,产品名称,产品制造商和产品类别。
它看起来像这样:
MariaDB [foundationtests]> select * from products_tbl;
+------------+--------------+----------------------+------------------+
| product_id | product_name | product_manufacturer | product_category |
+------------+--------------+----------------------+------------------+
| 12 | i5 | intel | computer |
| 14 | swimsuit | adidas | sports |
| 17 | Die Elfen | Heyne | books |
| 19 | Die Zwerge | Heyne | books |
| 20 | gym shoes | adidas | sports |
| 22 | i7 | intel | computer |
| 24 | i3 | intel | computer |
| 25 | rope | adidas | sports |
| 26 | Die Orks | Heyne | books |
| 27 | Die Drachen | Heyne | books |
| 28 | i8500 | intel | computer |
| 29 | bikershorts | adidas | sports |
+------------+--------------+----------------------+------------------+
12 rows in set (0.000 sec)
我基本上想运行以下查询:
$fetch = $connection->prepare("SELECT DISTINCT product_name
FROM products_tbl
WHERE product_manufacturer = ?
OR product_category = ?
OR IF NONE OF THESE EXISTS
BEFORE THE SELECTLIMIT WAS REACHED
SELECT ANY RECORD FROM
THE SPECIFIED COLUMN DISTINCT
FROM THE ALREADY FETCHED RESULTS
ORDER BY RAND()
LIMIT 6
");
使用一些简短的mysql语法可能吗?
编辑: 预期结果示例:
现在让我们假设product_manufacturer =吗?与“ intel”匹配,并且 product_category =?与“计算机”匹配。 在这种情况下,将选择4行,使我们得到“ i5,i7,i3,i8500”作为(随机)结果集。 但我要最少随机分配6行,例如“ i5,Die Elfen,i7,i3,泳装,i8500”。
如何在查询中实现?
编辑:这是一些扩展的示例数据,因为如果表上有足够的记录可能会返回带有实际匹配WHERE条件的记录的完整结果集,则一些问题会变得更加明显:
MariaDB [foundationtests]> select * from products_tbl;
+------------+--------------+----------------------+------------------+
| product_id | product_name | product_manufacturer | product_category |
+------------+--------------+----------------------+------------------+
| 12 | i5 | intel | computer |
| 14 | swimsuit | adidas | sports |
| 17 | Die Elfen | Heyne | books |
| 19 | Die Zwerge | Heyne | books |
| 20 | gym shoes | adidas | sports |
| 22 | i7 | intel | computer |
| 24 | i3 | intel | computer |
| 25 | rope | adidas | sports |
| 26 | Die Orks | Heyne | books |
| 27 | Die Drachen | Heyne | books |
| 28 | i8500 | intel | computer |
| 29 | bikershorts | adidas | sports |
| 30 | i7399 | intel | computer |
| 31 | i6400 | intel | computer |
| 32 | i5473 | intel | computer |
| 33 | i9876 | intel | computer |
| 34 | i8888 | intel | computer |
| 35 | i9076 | intel | computer |
+------------+--------------+----------------------+------------------+
答案 0 :(得分:2)
您可以将UNION ALL
与两个SELECT
查询一起使用;在第一个查询中,可以获得与匹配条件相对应的6行;我们还将获得另外一列matching
,通知我们结果来自匹配条件。
现在,在第二个查询中,传统方法是执行SELECT.. WHERE NOT EXISTS (..<matching condition SELECT query> ..) LIMIT 6
。然而,这将是相对低效的。因此,我们可以避免这种NOT EXISTS
条件,而是获取12行(是第一个查询行的两倍)。这样可以确保即使第二个查询返回了第一个查询的6行,我们仍然还有另外6个行的缓冲区。
请注意,没有LIMIT
的{{1}}是不确定的,但是由于您只想随机排序;我们可以通过内部ORDER BY
查询中的ORDER BY
来避免:
SELECT
答案 1 :(得分:2)
您可以使用条件排序:
select * from (
select product_name
from products_tbl
order by (product_manufacturer = 'Heyne' or product_category = 'computer') desc, rand()
limit 6
)t
order by rand()
请参见demo。