我的数据库中有两个表。每个都有三个东西:一个标识符,它只是一个自动生成的数字,一个文本字段和一个整数字段。文本字段中的数据(我们称之为Names
)在两个表中完全相同。只有数字字段不同。我需要语句来比较两组数字字段,并列出任何一个表中数字不为零的每个名称。我还需要它在字段中将两个数字加在一起,并使用组合值创建一个单独的列,并按照从最高值到最低值的值的顺序列出名称。
这是我已经得到的,现在我被卡住了,我是SQL的新手
SELECT tableone.names
FROM tableone, tabletwo
WHERE (tableone.numbers > 0) AND (tabletwo.numbers > 0)
答案 0 :(得分:1)
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 |
+-------+-------------+