mysql选择两个表,MySQL从两个表中选择

本文介绍如何在不使用JOIN的情况下从两个拥有相同字段但数据时期不同的表中选取所有数据,通过UNION操作实现,并探讨了在特定场景下避免JOIN提高查询速度的方法。还提供了将JOIN条件置于WHERE子句的建议,以优化查询性能。
摘要由CSDN通过智能技术生成

Can anybody tell me how to select data from two tables, without having to use join?

Something like this:

SELECT t1.*,

t2.*

FROM table1 t1,

table2 t2

Clarification

I have these two tables, that have the same fields. IE: table1 contains data from 2011 and table2 contains data in 2012. I want to get them all.

Further clarification:

The result set desired can be produced by:

(SELECT tr.full_name,tr.headlines,tr.content,tr.stamp,tr.person_key

FROM tbl_transactions tr

JOIN persons p ON p.person_key = tr.person_key

JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams')

WHERE t.team_key = '')

UNION

(SELECT tr.full_name,tr.headlines,tr.content,tr.stamp,tr.person_key

FROM tbl_transactions_bk_2012 tr

JOIN persons p ON p.person_key = tr.person_key

JOIN teams t ON (pp.membership_id = t.id and pp.membership_type = 'teams')

WHERE t.team_key = '')

and the OP wishes to see if there are alternative ways to speed this up ("I tried to use UNION in between those queries. but query speed took 0.1887 secs. it's kinda slow.")

(@Jetoox: if this is not your intent, please edit your question and clarify).

解决方案

Just put the join condition in the WHERE clause:

SELECT t1.*, t2.*

FROM table1 t1, table2 t2

WHERE t1.id = t2.t1_id

That is an inner join, though.

UPDATE

Upon looking at your queries: In this particular case, there is no relation between tbl_transactions and tbl_transactions_bk_2012 (i.e. joining these on person_key is meaningless because there is no relationship between the two tables in the way that (say) tbl_transactions and persons are related).

Then, you should use the UNION approach. Trying to join the first query to the second using either JOIN or FROM xx, yy WHERE xx.id=yy.id is meaningless and won't give you the results you need.

By the way, in the future, put your current query/attempt in your post - as you can see it will prevent you from getting answers that aren't appropriate for your question (as my first attempt was).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值