当只有一行存在时从MYSQL中选择

时间:2016-12-01 07:00:48

标签: php mysql database select

我有这个mysql查询:

SELECT a.full_address 
FROM games_server AS a 
JOIN orders_order AS b 
ON b.server_id = a.id 
WHERE service_type = 'color' 
AND status = 'running' ORDER BY RAND()"

只有当service_type为'color'时,它才能正常工作并选择一个值。 但我需要的是,只有当一行有service_type = color而没有其他行具有不同的service_type值时,才会选择'full_address'。因为对于一个full_address = a,可能有多行。例如。 full_address = a,service_type = color,相同的full_address = a,service_type = top。在那个特定的例子中,当有两个时 - 它不能被选中。仅当有一行具有service_type = color。

我希望任何人都明白我说的话。对不起,如果我不能让它更清楚。

2 个答案:

答案 0 :(得分:1)

试试这个(假设games_server有id):

SELECT a.full_address FROM games_server AS a 
JOIN orders_order AS b ON b.server_id = a.id 
WHERE status = 'running' 
GROUP BY a.id
HAVING group_concat(distinct service_type) = 'color'
ORDER BY RAND()

答案 1 :(得分:0)

如果我已正确理解您的问题,则子查询在此处应该有用。

SELECT a.full_address 
FROM games_server AS a 
JOIN orders_order AS b 
ON b.server_id = a.id 
WHERE service_type in 
        (select service_type 
         from orders_order 
         group by service_type 
         having COUNT(service_type)=1)
AND status = 'running' ORDER BY RAND()