我这里有一张 table :
activation
+--------+----------------+
| id | activation_code|
+--------+----------------+
| 0001 | 00111 |
| 0002 | 00110 |
| 0003 | 00100 |
+--------+----------------+
和另一个表:
device
+--------+--------------+
| id |activation_id |
+--------+--------------+
| 12121| 0001 |
| 12122| 0002 |
| 12123| 0003 |
| 12124| 0004 |
| 12125| 0005 |
+--------+--------------+
如果 device.activation_id == activation.id
,我如何获取这两个表并进行比较
我想单独列出这些设备,请参见示例:
devices
+--------+----------+
| active |inactive |
+--------+----------+
| 12121| 12124 |
| 12122| 12125 |
| 12123| |
| | |
| | |
+--------+----------+
在这种使用 PHP 的情况下,我如何使用内部联合来获得执行效率非常高的解决方案?
我这里有一个解决方案,但不是很好:
foreach ($device_query as $res_d) {
foreach ($activation_query as $res_a) {
if ($res_d->activation_id == $res_a->id) {
$is_active = true;
break;
}
else {
$is_active = false;
}
}
}
最佳答案
您可以在一个 SQL Select 中执行此操作,以获取两个设备:
select
if(activation_code is not null, d.id, null) as active,
if(activation_code is null, d.id, null) as inactive,
activation_code
from device d
left join activation a
on a.id = d.activation_id
如果你想查看结果:http://sqlfiddle.com/#!9/79abb6/13
关于php - 如何使用 INNER JOIN 比较表并返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32687231/