我有三个表(deb
,dos
,char
),我正在寻找一个SQL查询来获取result
表,如下所示:
table: deb
+----+-------------+--------+
| id | label | dos_id |
+----+-------------+--------+
| 1 | right | 1 |
| 2 | left | 2 |
+----+-------------+--------+
table:char
+----+-------------+--------+
| id | name | dos_id |
+----+-------------+--------+
| 1 | jack | 1 |
| 2 | thaw | 1 |
| 3 | lbaz | 2 |
| 4 | amar | 3 |
+----+-------------+--------+
table:dos
+----+-------------+
| id | color |
+----+-------------+
| 1 | black |
| 2 | white |
+----+-------------+
result table
+----+-------------+--------+
| id | color | value |
+----+-------------+--------+
| 1 | black | right |
| 1 | black | jack |
| 1 | black | thaw |
| 2 | white | left |
| 2 | white | lbaz |
| 2 | white | amar |
+----+-------------+--------+
我尝试左右加入,但它没有用。
我正在寻找的是,对于每个dos
行,我在其他列中得到相应的char
和deb
值。
也许在一个行中选择查询可能有所帮助。我不知道。
请帮帮我,谢谢。
答案 0 :(得分:1)
您需要运行2个单独的查询,并将结果组合到一个结果集中。您可以使用UNION运算符执行此操作,如下所示:
SELECT * FROM
(
SELECT dos.id id, dos.color color, deb.label value
FROM dos INNER JOIN deb on dos.id = deb.dos_id
UNION
SELECT dos.id id, dos.color color, char.name value
FROM dos INNER JOIN char on dos.id = char.dos_id
)
ORDER BY id
编辑:
SELECT *
FROM
(
SELECT dos.id AS id, dos.date_facture AS facture, deb.libelle AS lbl, '' AS nom
AS lbl FROM jos_tktransit_dossier dos INNER JOIN jos_tktransit_deboure deb ON dos.id = deb.id_dossier
UNION
SELECT dos.id AS id, dos.date_facture AS facture, '' AS lbl, charg.nom_charge AS nom
FROM jos_tktransit_dossier dos INNER JOIN jos_tktransit_charge_assistance charg ON dos.id = charg.id_dossier
)
答案 1 :(得分:0)
可能是这样的:
SELECT dos.id, color, deb.label as value FROM dos, deb WHERE dos_id = dos.id
UNION SELECT dos.id, color, char.name as value FROM dos, char WHERE dos_id = dos.id;
答案 2 :(得分:0)
尝试以下方法:
(select d.id,d.color,c.name
from dos d , char1 c
where d.id=c.dos_id) union
(select d.id,d.color,e.label
from dos d, deb e
where d.id= e.dos_id)
这应该输出以下内容:
ID COLOR NAME
1 black jack
1 black right
1 black thaw
2 white lbaz
2 white left
...但它没有按照正确的顺序显示值:
+----+-------------+--------+
| id | color | value |
+----+-------------+--------+
| 1 | black | right |
| 1 | black | jack |
| 1 | black | thaw |
| 2 | white | left |
| 2 | white | lbaz |
| *2 | white | amar* |
+----+-------------+--------+