1

我的数据库中有两个表。每个都包含三件事:一个标识符,它只是一个自动生成的数字,一个文本字段和一个整数字段。两个表中的文本字段(我们称之为Names)中的数据完全相同。只有数字字段不同。我需要这些语句来比较两组数字字段,并列出任一表中数字不为零的每个名称。我还需要它在字段中将两个数字相加,并用组合值创建一个单独的列,并按从最高值到最低值的顺序列出名称。

据我所知,现在我被卡住了,我对 SQL 很陌生

SELECT tableone.names
FROM tableone, tabletwo
WHERE (tableone.numbers > 0) AND (tabletwo.numbers > 0)
4

1 回答 1

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 |
+-------+-------------+
于 2013-05-31T21:17:42.327 回答