我目前有一个浓度表,它与一个元素表相关联。有一个集中表
|conc_id|element_id|conc|
和元素表
|element_id|symbol|
浓度表仅具有每个浓度非零的conc_id的element_ids。
我要做的是创建一个查询,对于每个concentration_id,将按顺序列出所有元素及其浓度,无论它们是否为非零。我已经尝试了许多日益复杂的方法(从RIGHT JOIN
开始),但是当它中没有任何元素时,它总是输出一个NULL conc_id。我正在寻找的输出是这样的:
|conc_id|element_id|symbol|conc|
|1 |1 |H |1.2 |
|1 |2 |He |NULL|
|1 |3 |Li |2.3 |
...
|3 |1 |H |4.5 |
|3 |2 |He |NULL|
|3 |3 |Li |NULL|
...
等等。有没有办法可以在没有NULL conc_id的情况下做到这一点?
感谢您提前提供任何帮助......
答案 0 :(得分:3)
首先,您必须构建一个包含conc_id
和element_id
之间所有组合的表格:
SELECT DISTINCT conc_id, elements.element_id FROM concentrations, elements;
其中给出了下表:
| conc_id | element_id |
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
...
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
...
一旦你有这样一张桌子,用浓度和元素加入它应该相当简单。例如:
SELECT combinations.conc_id, combinations.element_id, symbol, conc
FROM
(SELECT DISTINCT conc_id, elements.element_id FROM concentrations, elements) AS combinations
LEFT JOIN concentrations ON (combinations.conc_id = concentrations.conc_id AND combinations.element_id = concentrations.element_id)
LEFT JOIN elements ON (combinations.element_id = elements.element_id);
结果:
| conc_id | element_id | symbol | conc |
| 1 | 1 | H | 1.2 |
| 1 | 2 | He | NULL |
| 1 | 3 | Li | 2.3 |
...
| 3 | 1 | H | 4.5 |
| 3 | 2 | He | NULL |
| 3 | 3 | Li | NULL |
...
答案 1 :(得分:0)
老实说,我认为最好的方法是在conc列中用零值实际填写缺失的数据。否则,你试图破解它以显示你实际上没有的数据,而且无论如何都要比保留空值更有形......
当然,假设没有性能考虑,这会妨碍。
答案 2 :(得分:0)
select conc_id, conc.element_id, symbol, concentration from concentration_table as conc
join element_table as elem on conc.element_id = elem.element_id
order by conc.conc_id asc
这给了我这张表:
conc_id element_id concentration element_id symbol
1 1 1.2 1 H
1 2 0 2 He
1 3 2.3 3 Li
3 1 4.5 1 H
3 2 0 2 He
3 3 0 3 Li
这些是起始表:
element_table:
element_id symbol
1 H
2 He
3 Li
浓度表:
conc_id element_id concentration
1 1 1.2
1 2 0
1 3 2.3
3 1 4.5
3 2 0
3 3 0
编辑:编辑查询以获取所请求的正确表值
答案 3 :(得分:0)
假设你没有一个简单的所有conc_id列表,你可以尝试类似的东西:
SELECT c.conc_id, e.element_id, e.symbol, c2.conc
FROM
(SELECT DISTINCT conc_id FROM concentration c) c
INNER JOIN element e
LEFT JOIN concentration c2 ON c2.conc_id = c.conc_id AND c2.element_id = e.element_id
ORDER BY c.conc_id, e.element_id
逻辑是:
如果你有另一个包含所有conc_id的表,你可以完全避免派生表。