简体   繁体   English

将两个SQL查询与不同的where和返回的唯一行组合在一起

[英]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 . 预期结果:我期望从选择所有列historylive在那里的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'shistory不存在中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... 但我想你应该用更多细节描述你的问题......

Assuming both tables have the same columns, it sounds like you want to use a UNION here. 假设两个表都有相同的列,听起来你想在这里使用UNION

SELECT Col1, Col2, ..., ColN
    FROM history 
    WHERE ID = 56
UNION
SELECT Col1, Col2, ..., ColN
    FROM live
    WHERE ID = 56 
        AND ACTIVE = 0 
        AND Shown = 'complete'

If the history and live tables have the same number (and preferably type) of columns, then a UNION query might be what you want: 如果historylive表具有相同数量(并且最好是类型)的列,那么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 如果historylive有相同的然后具有相同数量(并且优选类型)的列,那么这可以帮助您

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM