SELECT
tableone.names,
tableone.numbers + tabletwo.numbers AS numbers_sum
FROM tableone
LEFT JOIN tabletwo USING (names)
WHERE (tableone.numbers > 0)
AND (tabletwo.numbers > 0)
ORDER BY 2 DESC
更新、テスト済みのSQL:
USE test;
CREATE TABLE IF NOT EXISTS tableone (
names TINYTEXT NOT NULL,
numbers INT NOT NULL,
PRIMARY KEY (names(100))
);
CREATE TABLE IF NOT EXISTS tabletwo (
names TINYTEXT NOT NULL,
numbers INT NOT NULL,
PRIMARY KEY (names(100))
);
INSERT INTO tableone SELECT 'a', RAND();
INSERT INTO tableone SELECT 'b', RAND();
INSERT INTO tableone SELECT 'c', RAND();
INSERT INTO tableone SELECT 'd', RAND();
INSERT INTO tabletwo SELECT names, RAND() FROM tableone;
SELECT
tableone.names,
tableone.numbers + tabletwo.numbers AS numbers_sum
FROM tableone
LEFT JOIN tabletwo USING (names)
WHERE (tableone.numbers > 0)
AND (tabletwo.numbers > 0)
ORDER BY 2 DESC;
出力:
+-------+-------------+
| names | numbers_sum |
+-------+-------------+
| b | 2 |
| d | 2 |
+-------+-------------+