[英]Combining Two SQL Queries with different where and returning unique rows
I'm trying to combine these 2 SQL queries. 我正在尝试组合这两个SQL查询。
SELECT * FROM `history` WHERE `ID` = 56
SELECT * FROM `live` WHERE `ID` = 56 AND `ACTIVE` = 0 AND t1.`Shown` = 'complete'
I've tried doing something like this: 我尝试过这样的事情:
SELECT t1.*,t2.*
FROM `history` t1
JOIN `live` t2
ON t1.`ID` = 56 AND t1.`ACTIVE` = 0 AND t1.`Shown` = 'complete'
WHERE t2.`ID` = 56
But the query above results in selecting everything from live
and forgetting about history
. 但是上面的查询导致从
live
和忘记history
中选择所有内容。
Expected result: I expect to select all columns from history
and live
where the ID is equal to 56
. 预期结果:我期望从选择所有列
history
和live
在那里的ID is equal to 56
。 But there will be scenarios where the ID's
in history
don't exist in live
-- in which case I want to select all from history
where the ID
is equal. 但会有场景中的
ID's
在history
不存在中live
-在这种情况下,我想从所有选择history
,其中ID
是相等的。
Both tables have different columns. 两个表都有不同的列。 The only thing that they have in common is the
ID
. 他们唯一的共同点就是
ID
。
Solution: 解:
Using UNION with specific columns from both tables.
Quick answer is: 快速回答是:
SELECT t1.*,t2.*
FROM `live` t1
JOIN `history` t2
ON t1.id = t2.id
WHERE t2.`ID` = 56 AND t1.`ACTIVE` = 0 AND t1.`Shown` = 'complete'
But I guess you should describe your problem with some more details... 但我想你应该用更多细节描述你的问题......
If the history
and live
tables have the same number (and preferably type) of columns, then a UNION
query might be what you want: 如果
history
和live
表具有相同数量(并且最好是类型)的列,那么UNION
查询可能是您想要的:
SELECT * FROM `history` WHERE `ID` = 56
UNION ALL
SELECT * FROM `live` WHERE `ID` = 56 AND `ACTIVE` = 0 AND t1.`Shown` = 'complete'
If the number of columns are not the same, then you can choose the same number of columns from both tables to make the query work. 如果列数不相同,则可以从两个表中选择相同数量的列以使查询起作用。
If history
and live
have same then have the same number (and preferably type) of columns then this could help you 如果
history
和live
有相同的然后具有相同数量(并且优选类型)的列,那么这可以帮助您
SELECT * FROM
(
SELECT * FROM `history` WHERE `ID` = 56
UNION ALL
SELECT * FROM `live` WHERE `ID` = 56 AND `ACTIVE` = 0 AND t1.`Shown` = 'complete'
) as result
OR 要么
SELECT * FROM
history h JOIN live l ON
h.id = l.id
WHERE h.id = 56 AND l.id= 56 AND l.`ACTIVE` = 0 AND l.`Shown` = 'complete'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.