具有WHERE条件

时间:2016-09-03 12:09:07

标签: mysql

当我在查询下面单独运行时,获得正确的结果。

SELECT COUNT(hospital_id) FROM `hospital` WHERE org_id='1' // Result: 0
SELECT COUNT(pharmacy_id) FROM `pharmacy` WHERE org_id='1' // Result: 1
SELECT COUNT(fire_station_id) FROM `fire_station` WHERE org_id='1' // Result: 3
SELECT COUNT(als_id) FROM `als` WHERE org_id='1' // Result: 3
SELECT COUNT(units_id) FROM `units` WHERE org_id='1'; //Result: 3

但我需要使用MySQL的任何概念单独使用所有结果。

我的尝试:

SELECT COUNT(hospital_id) AS Hospital FROM `hospital` WHERE org_id='1'
UNION
SELECT COUNT(pharmacy_id) AS Pharmacy FROM `pharmacy` WHERE org_id='1'
UNION
SELECT COUNT(fire_station_id) AS Station FROM `fire_station` WHERE org_id='1'
UNION
SELECT COUNT(als_id) AS Als FROM `als` WHERE org_id='1'
UNION
SELECT COUNT(units_id) AS Units FROM `units` WHERE org_id='1';

这是我目前的结果:

    +------------+
    |   Hospital |
    +------------+
    |          0 |
    |          1 |
    |          3 |
    +------------+

这是我想要的结果:

+------------+------------+------------+-------+--------+
|   Hospital |   Pharmacy |   Station  |  Als  |   Units|
+------------+------------+------------+-------+--------+
|          0 |          1 |         3  |     3 |      3 |
+------------+------------+------------+-------+--------+

我也参考了堆栈问题Count rows in more than one table with tSQL 但没有得到理想的结果。 请更新我的查询或建议任何其他MySQL概念。

感谢所有人!

2 个答案:

答案 0 :(得分:2)

您的特定查询存在问题UNION。使用UNION ALL。实际上,始终使用UNION ALL,除非您特别想要承担删除重复项的开销。

无论如何,您的查询都很接近。将它们作为子查询放在SELECT

SELECT (SELECT COUNT(hospital_id) AS Hospital FROM `hospital` WHERE org_id='1') as hospital,
       (SELECT COUNT(pharmacy_id) AS Pharmacy FROM `pharmacy` WHERE org_id='1') as pharmacy,
       (SELECT COUNT(fire_station_id) AS Station FROM `fire_station` WHERE org_id='1') as Station,
       (SELECT COUNT(als_id) AS Als FROM `als` WHERE org_id='1') as als,
       (SELECT COUNT(units_id) AS Units FROM `units` WHERE org_id='1') as units;

您还可以将子查询放在FROM子句中,并使用CROSS JOIN将它们组合起来。

答案 1 :(得分:1)

试试这个:

<?php
 $string = "image2";

 // I need some function to display the image2 on my webpage.
 // If string "image2" is found in the uploads folder
 // then it should display the image 

?>