我正在尝试从两个不同的表中查询两个不同的列,我可以在其中计算某些列的数量。我可以在两个单独的查询中执行此操作,但我认为这会在将来导致速度降低。我想要的是一个查询,我只能在一个查询中显示这两个计数。
我尝试使用两个分开的选择语句,但是我认为这不好,我也尝试使用Union All,但是结果不是我期望的。
upload_monitoring (12 Columns)
upm_FileName | upm_Status
----------------+--------------
Monitoring_0608 | Distributed
Monitoring_0607 | Distributed
Monitoring_0606 | Distributed
Monitoring_0605 | Uploaded
(100 rows)
distribute_monitoring (7 Columns)
dist_ProductName | dist_Status
-------------------+--------------
Monitoring_0608 | Pending
Monitoring_0607 | Pending
Monitoring_0606 | Pending
Monitoring_0605 | Touched
(100 rows)
我尝试了这些:
$query2 = "
SELECT
COUNT(upm_Status) AS total_DistItems
FROM
upload_monitoring
WHERE
upm_Status = 'Distributed'
AND
upm_FileName = '$upm_FileName'
";
$result2 = mysqli_query($connection, $query2);
$fetchResult2 = mysqli_fetch_assoc($result2);
$total_DistItems = $fetchResult2['total_DistItems'];
$query3 = "
SELECT
COUNT(dist_Status) AS total_PendItems
FROM
distribute_monitoring
WHERE
dist_Status = 'Pending'
AND
dist_Product = '$upm_FileName'
";
$result3 = mysqli_query($connection, $query3);
$fetchResult3 = mysqli_fetch_assoc($result3);
$total_PendItems = $fetchResult3['total_PendItems'];
我也尝试过这些
$query2 = "
SELECT
upm_Status,
COUNT(upm_Status) AS total_DistItems
FROM
upload_monitoring
WHERE
upm_Status = 'Distributed'
AND
upm_FileName = '$upm_FileName'
UNION ALL
SELECT
dist_Status,
COUNT(dist_Status) AS total_PendItems
FROM
distribute_monitoring
WHERE
dist_Status = 'Pending'
AND
dist_Product = '$upm_FileName'
";
$result2 = mysqli_query($connection, $query2);
无论结果如何
upm_Status | total_DistItems
------------+--------------
Distributed | 34
Pending | 12
我希望结果像这样。
upm_Status | total_DistItems | dist_Status | total_PendItems
------------+-----------------+-------------+-----------------
Distributed | 34 | Pending | 12
答案 0 :(得分:1)
这是一种方法:
SELECT u.*, d.*
FROM (SELECT 'Distributed' as upm_Status,
COUNT(*) AS total_DistItems
FROM upload_monitoring
WHERE upm_Status = 'Distributed' AND
upm_FileName = ?
) u CROSS JOIN
(SELECT 'Pending' as dist_Status, COUNT(dist_Status) AS total_PendItems
FROM distribute_monitoring
WHERE dist_Status = 'Pending' AND
dist_Product = ?
) d;
请注意,我将$upm_filename
替换为?
。这表明您应该使用参数将值传递到查询中,而不是使用此类值来修饰查询字符串。您的方法会使您面临意外语法错误和SQL注入攻击的风险。