我想对一个查询进行双重选择。我进行了很多搜索,但没有找到适合我的解决方案。
这是我拥有的代码:
$stmt = $db->prepare('SELECT * FROM products p
INNER JOIN products_lang pl ON p.id_product = pl.id_product
WHERE pl.id_lang = ? AND p.sold = ? AND p.featured = ?
ORDER BY p.date_insert DESC,p.id_product DESC
LIMIT 10');
$stmt->execute(1,0,1);
$rows_feat = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $db->prepare('SELECT * FROM products p
INNER JOIN products_lang pl ON p.id_product = pl.id_product
WHERE pl.id_lang = ? AND p.sold = ?
ORDER BY p.date_insert DESC,p.id_product DESC
LIMIT 10');
$stmt->execute(1,0);
$rows_last = $stmt->fetchAll(PDO::FETCH_ASSOC);
我可以在一个查询中执行这样的结果吗?有可能吗?
$rows['feat'] = Array
$rows['last'] = Array
谢谢
答案 0 :(得分:0)
考虑到这一点:
...我认为保存数据库往返的最直接方法是一个很好的旧联盟。如果您实际上使用的是SELECT *
,那么获得最终订单会很棘手,因为您将有重复的列名:
(
SELECT 'feat' AS type_,
p.date_insert AS sort_date_, p.id_product AS sort_id_
p.*, pl.*
FROM products p
INNER JOIN products_lang pl ON p.id_product = pl.id_product
WHERE pl.id_lang = ? AND p.sold = ? AND p.featured = ?
ORDER BY p.date_insert DESC, p.id_product DESC
LIMIT 10
) UNION ALL (
SELECT 'last' AS type_,
p.date_insert AS sort_date_, p.id_product AS sort_id_
p.*, pl.*
FROM products p
INNER JOIN products_lang pl ON p.id_product = pl.id_product
WHERE pl.id_lang = ? AND p.sold = ?
ORDER BY p.date_insert DESC,p.id_product DESC
LIMIT 10
)
ORDER BY type_, sort_date_ DESC, sort_id_ DESC
然后,您需要丢弃或忽略结果集中的辅助列。
我建议您尝试使用大型数据集对这两种选择进行基准测试,以确保这实际上更快。