MySQL:如何从多行中选择一个首选值(并回退到默认值)?

时间:2011-07-01 10:44:14

标签: mysql sql

我有以下查询,它返回附加到IN子句中指定的产品ID的组ID列表。

SELECT t1.product_id, t2.group_id  
FROM table_1 t1  
LEFT JOIN table_2 t2  
ON t1.product_id = t2.product_id  
WHERE t1.product_id IN(1,2,3,4,5)  
AND t2.group_id = -1  
OR t2.group_id = 2

这将返回以下内容:

+------------+----------+
| product_id | group_id |
+------------+----------+
| 1          | -1       |
| 1          |  2       |
| 2          | -1       |
| 3          | -1       |
| 4          | -1       |
| 5          | -1       |
+------------+----------+

group_id的默认值始终为-1,但在某些情况下可能有多个值(例如,product_id'1'的group_id为'-1'和'2')。我想要做的是在有替代方案时忽略'-1'值,所以我最终得到这个:

+------------+----------+
| product_id | group_id |
+------------+----------+
| 1          |  2       |
| 2          | -1       |
| 3          | -1       |
| 4          | -1       |
| 5          | -1       |
+------------+----------+

我尝试在product_id上使用GROUP BY语句,但我最终得到了group_id列中的-1值。

请有人可以给我一些关于如何做到这一点的指示!

4 个答案:

答案 0 :(得分:0)

SELECT t1.product_id, MAX(t2.group_id)  
FROM table_1 t1 , table_2 t2   
WHERE t1.product_id IN(1,2,3,4,5) 
AND t1.product_id = t2.product_id 
AND t2.group_id = -1  
OR t2.group_id = 2
GROUP BY (t1.product_id)

试试这个。如果-1和2都可用,则返回2。即,我只选择可用组ID的最大值。希望这是你需要的

答案 1 :(得分:0)

SELECT t1.product_id, COALESCE(MAX(t2.group_id ),-1) AS group_id -- if there is no group id default to -1
FROM table_1 t1  
LEFT JOIN table_2 t2  
ON t1.product_id = t2.product_id  
WHERE t1.product_id IN(1,2,3,4,5)  
AND t2.group_id IN (-1, 2)
GROUP BY t1.product_id

答案 2 :(得分:0)

你可以使用这个sql:

SELECT t1.product_id, t2.group_id  
FROM table_1 t1  
LEFT JOIN (SELECT product_id, MAX(group_id) AS group_id
           FROM table_2
           WHERE group_id IN (-1,2)
           GROUP BY product_id) t2 ON t1.product_id = t2.product_id  
WHERE t1.product_id IN (1,2,3,4,5)

答案 3 :(得分:0)

试试这个,

SELECT product_id, group_id= '-1' From products GROUP BY product_id HAVING COUNT(product_id) = 1 
UNION 
SELECT product_id, MAX(group_id) FROM products GROUP BY product_id HAVING COUNT(product_id) > 1