gpt4 book ai didi

mysql - 从两个表中选择整行

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:22 25 4
gpt4 key购买 nike

我不知道这是否可能,我可能会在这里问一个愚蠢的问题,如果是这样,请原谅我。
我有两个有点相似但不完全相似的表。
表一(用户意见)

    | o_id     | user_id | opinion      |is_shared_from| date,isglobal etc
|:---------|---------|:------------:|:------------:|
| 1 | 11| text 1 | 0
| 2 | 13| text 2 | 2
| 3 | 9| text 3 | 0

表 2(Buss_opinions)

    | bo_id    | o_id   | user_id      | opinion    | date
|:---------|--------|:------------:|:------------:|
| 1 | 2| 52 | bus text 1
| 2 | 3| 41 | bus text 2

如果我像这样进行标准选择和加入:

SELECT * FROM user_opinions uo
JOIN Buss_opinions bo
ON uo.o_id = bo.o_id

这将返回两个表的数据连接在一起的行。

我的问题是,如果我想从这两个表的不同行中获取数据怎么办。结果应该是这样的:

| oid      | bo_id   | opinion      | nb: and other rows from both tables
|:---------|---------|:------------:|
| 1 | NULL | text 1 | nb:from table 1
| NULL | 1| bus text 1| nb:from table 2
| 2 | NULL | text 2 |nb:from table 1

等等

它获取表的数据和没有公共(public)字段的地方,它在字段中放置一个 NULL 值。是否有一种连接类型?还是有其他方法可以做到这一点?

最佳答案

您可以采用的一种方法是使用 UNION (http://dev.mysql.com/doc/refman/5.0/en/union.html):

SELECT oid AS OID, null AS BOID, user_id AS USERID, opinion AS Opinion
FROM table1
UNION
SELECT null AS OID, bo_id AS BOID, user_id AS USERID, opinion AS Opinion
FROM table2

编辑:您甚至可以更进一步,将其与 CONCAT 函数结合使用:

SELECT CONCAT('OID-', oid) AS ID, user_id AS USERID, opinion AS Opinion
FROM table1
UNION
SELECT CONCAT('BOID-', bo_id) AS ID, user_id AS USERID, opinion AS Opinion
FROM table2

关于mysql - 从两个表中选择整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14718613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com