web-dev-qa-db-fra.com

COUNT (*) à partir de plusieurs tables dans MySQL

Comment dois-je procéder pour sélectionner COUNT (*) s à partir de plusieurs tables dans MySQL?

Tel que:

SELECT COUNT(*) AS table1Count FROM table1 WHERE someCondition
JOIN?? 
SELECT COUNT(*) AS table2Count FROM table2 WHERE someCondition
CROSS JOIN? subqueries?
SELECT COUNT(*) AS table3Count FROM table3 WHERE someCondition

Modifier:

Le but est de rendre ceci:

+-------------+-------------+-------------+
| table1Count | table2Count | table3Count |
+-------------+-------------+-------------+
| 14          | 27          | 0           |
+-------------+-------------+-------------+
40
bcmcfc

Vous pouvez le faire en utilisant des sous-requêtes, une sous-requête pour chaque table

SELECT
  (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count, 
  (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count,
  (SELECT COUNT(*) FROM table3 WHERE someCondition) as table3Count
90
Julien Hoarau

Vous pouvez le faire avec des sous-requêtes, par exemple:

select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count, 
       (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count 
11
RedFilter

Vous pouvez utiliser UNION

  SELECT COUNT(*) FROM table1 WHERE someCondition
  UNION
  SELECT COUNT(*) FROM table2 WHERE someCondition
  UNION
  SELECT COUNT(*) FROM table3 WHERE someCondition
5
Interfector

Essayez de changer pour:

SELECT 
    COUNT(table1.*) as t1,
    COUNT(table2.*) as t2,
    COUNT(table3.*) as t3 
FROM table1 
    LEFT JOIN tabel2 ON condition
    LEFT JOIN tabel3 ON condition
1
Pramendra Gupta