[英]Joining multible tables with unequal field's in mysql
I have tried some time now. 我已经尝试了一段时间。 I tried UNION and fake (one left and one right join) full join's.
我尝试了UNION并伪造了(一个左连接和一个右连接)完全连接。 Im not that good with sql so maybe i stumbled over the solution but couldn't do it right.
我对sql不太好,所以也许我偶然发现了该解决方案,但做不到。
For this example i have three tables (i probably have more with the time). 对于此示例,我有三个表(时间可能会更多)。
post:
----------------------------
| type | rel_id | id |
----------------------------
| video | 2 | 51 |
|----------------------------|
| text | 1 | 50 |
----------------------------
video:
----------------------------
| id | video_url | title |
----------------------------
| 2 | ... | ... |
|----------------------------|
| 1 | ... | ... |
----------------------------
text:
----------------
| id | contend |
----------------
| 2 | ... |
|----------------|
| 1 | ... |
----------------
The post table is the main table. 发布表是主表。 The type field shows what table to join with.
类型字段显示要连接的表。 the field rel_id says what row to connect to.
字段rel_id表示要连接到的行。
I could use some output like this: 我可以这样使用一些输出:
------------------------------------------
| id | type | video_url | title | contend |
------------------------------------------
| 51 | video | ... | ... | NULL |
|------------------------------------------|
| 50 | text | NULL | NULL | ... |
------------------------------------------
The last problem is that the last WHERE clause need to be free so that i can use it for searching all results. 最后一个问题是最后一个WHERE子句需要是自由的,以便我可以用它来搜索所有结果。
You could try: 您可以尝试:
SELECT p.id AS id, p.type AS type, v.video_url AS video_url,
v.title AS title, NULL AS contend
FROM post p INNER JOIN video v
ON p.rel_id = v.id AND p.type = 'video'
UNION
SELECT p.id, p.type, NULL, NULL, t.contend
FROM post p INNER JOIN text t
ON p.rel_id = t.id AND p.type = 'text'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.