我的查询是:
SELECT * FROM `table` WHERE `id` IN (1,2,1,3,4,5,2);
我需要返回带有重复项的结果。
这里我的结果需要返回id = 1或id = 2行两次,其他行。
答案 0 :(得分:1)
您需要使用UNION ALL
,并为要复制的每个id
添加单独的查询。
SELECT * FROM `table` WHERE `id` IN (1,2,3,4,5)
UNION ALL
SELECT * FROM `table` WHERE `id` IN (1, 2)
另一种方法是使用包含重复项的合成表进行连接:
SELECT t1.*
FROM `table` AS t1
JOIN (SELECT 1 AS id
UNION ALL
SELECT 2
UNION ALL
SELECT 1
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 2) AS t2
ON t1.id = t2.id
另一种方法是在处理结果时在PHP中复制行。所以你可以有一个像这样的数组:
$ids = array(1, 2, 1, 3, 4, 5, 2);
$id_counts = array_count_values($ids);
$all_results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$all_results = array_merge($all_results, array_fill(0, $id_counts[$row['id']], $row));
}