用于连接两个表的mysql查询

时间:2017-03-16 05:37:38

标签: php mysql

company_name | macid          |  expiry_date
---------------------------------------------
abc          |  123456789012  |  2017-03-23
qwe          |  987654321012  |  2018-05-24
asd          |  456789123012  |  2019-07-07
abc          |  789456123000  |  2017-03-23
abc          |  445544444444  |  2018-03-03
abc          |  555555555555  |  2017-03-25


company_name | desktop         | server 
abc            123456789012      555555555555
               789456123000

我有两个表,我想要table1和table2中存在的所有macid和expiry日期。此外,我将所有macid作为新行和桌面macid和服务器macid存储在不同的列中。我的查询

"select a.macid,a.expity_date from table1 a,table2 b where a.macid like b.desktop or a.macid like %'b.server%'"

但显示结果为null。请帮忙解决。

我想要结果

 macid          |  expiry_date
---------------------------------------------
 123456789012  |  2017-03-23
 789456123000  |  2017-03-23 
 555555555555  |  2017-03-25 

对于table2,如果我想搜索mac_id,我必须使用

"select * from table2 where desktop like '%123456789012%'"

我无法检索没有%(百分比)的记录

3 个答案:

答案 0 :(得分:2)

我认为这只是一个错字,而不是expity_date,在您的查询中expiry_date,请参阅demo

select a.macid, a.expiry_date
from table1 a, table2 b
where a.macid like b.desktop or a.macid like b.server

但是,最好使用join而不是逗号(,)来加入内容:

select a.macid, a.expiry_date
from table1 a
join table2 b
on a.macid like b.desktop or a.macid like b.server

另请在此处查看demo  另一件事是如果desktopservermacid相同,那么使用等号(=)也可以。

答案 1 :(得分:1)

您必须分别制作两个JOIN然后UINON个结果。

SELECT macid, expiry_date
FROM table1 JOIN table2
ON table1.macid = table2.desktop
UNION
SELECT macid, expiry_date
FROM table1 JOIN table2
ON table1.macid = table2.server

以下是工作演示:http://sqlfiddle.com/#!9/dccea43/1

答案 2 :(得分:0)

试试这个:

__declspec(selectany) const int X = 123;
相关问题