简体   繁体   English

如果第一个表在MySQL查询中使用UNION没有返回记录,如何从另一个表中获取记录

[英]How to fetch record from another table if first table return no record using UNION in MySQL query

I have two table name 'activites' & 'archived_activities'. 我有两个表名'activites'和'archived_activities'。 I devide my activities table record into another table record. 我将我的活动表记录分成另一个表记录。 Activities table contain only first 200 latest activities of users and remaining record moved to archived_activities table. 活动表仅包含用户的前200个最新活动,并且剩余记录已移至archived_activities表。 Now I want to join both table only when activities table return null then I want to use same offset and limit for archived_activities table to fetch next record. 现在我只想在活动表返回null时加入两个表,然后我想使用相同的偏移量和限制来获取archived_activities表以获取下一条记录。 Below I my query that is not working fine. 在我下面我的查询不能正常工作。

SELECT * FROM activities WHERE user_id=87 LIMIT 180,20
UNION ALL 
SELECT * FROM activities WHERE user_id=87 LIMIT 180,20

But this query working not fine. 但是这个查询工作不顺利。

Any help? 有帮助吗?

One approach here would be to do a union to get both current and archived records into one logical table, but to order them such that current records get higher priority, should they exist. 这里的一种方法是进行联合以将当前记录和归档记录都放入一个逻辑表中,但是对它们进行排序以使当前记录具有更高的优先级(如果它们存在)。 I assign a position of 1 to current records and 2 to archived records. 我将1的位置分配给当前记录,将2分配给归档记录。 Then, I order by this position and retain 200 records. 然后,我按此位置订购并保留200条记录。

SELECT col1, col2, ...
FROM
(
    SELECT col1, col2, ..., 1 AS position
    FROM activities
    WHERE user_id = 87
    UNION ALL
    SELECT col1, col2, ..., 2
    FROM archived_activities
    WHERE user_id = 87
) t
ORDER BY
    position
LIMIT 200;

You can use NOT EXISTS() : 你可以使用NOT EXISTS()

SELECT * FROM activities
WHERE user_id=87
LIMIT 180,20
UNION ALL 
SELECT * FROM archieve_activities 
WHERE NOT EXISTS(SELECT 1 FROM activities 
                 WHERE user_id = 87)
  AND user_id=87
LIMIT 180,20

You can try this query 您可以尝试此查询

select * from activities as a 
union all
select * from archived_activities as b 
where b.user_id not in 
(select r.user_id
 from activities as r)

Neither of the UNION Answers does the LIMIT 180, 20 optimally for the general case. 对于一般情况LIMIT 180, 20 UNION Answers都没有最佳地执行LIMIT 180, 20

( SELECT ... ORDER BY .. LIMIT 200 )
UNION ALL
( SELECT ... ORDER BY .. LIMIT 200 )
ORDER BY .. LIMIT 180, 20

This will get the 'right' 20 rows regardless of whether either SELECT finds less than, or more than, 200 rows. 无论SELECT是否发现少于或多于200行,这将获得“正确”的20行。

(Note, the '200' comes from '180+20'.) (注意,'200'来自'180 + 20'。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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