这是我的两张 table 。我不确定它们是否正确标准化:
all_configurator_lasers_power:
laser_id | power_id | laser_configuration
=========================================
1 10 1
1 25 1
1 20 2
1 50 2
2 10 1 ...
all_configurator_power_text:
power_id | power_level | laser_configuration | power_text
=========================================================
10 10 watts 1 10 watt text
25 25 watts 1 25 watt text
20 20 watts 2 20 watt text
50 50 watts 2 50 watt text
如果我在第一个表中提供 laser_id,我想要返回的是第二个表的前两行。
这是我试过的(但没用)
'SELECT * FROM all_configurator_power_text
INNER JOIN all_configurator_power_text
ON all_configurator_lasers_power.laser_configuration = all_configurator_power_text.laser_configuration'
这会返回一个像这样的数组:
Array (
[0] => stdClass Object
(
[id] => 1
[language] => en
[power_id] => 10
[power_level] => 10 watts
[laser_configuration] => 1
[power_text] => 10 watt text
[laser_id] => 1
)
...)
但数组(一个 CodeIgniter 对象)也返回 laser_configuration 为 2 的对象。我只想要 1 的对象。我添加了 WHERE laser_configuration = 1
的 WHERE 子句,但后来我得到了非对象错误。
我做错了什么?
最佳答案
您需要在 WHERE
子句中指定您正在使用哪个表的 laser_configuration
。这样做,它应该适用于您编写的子句。
所以你最终会得到这样的东西:
SELECT * FROM all_configurator_power_text
INNER JOIN all_configurator_lasers_power
ON all_configurator_lasers_power.laser_configuration = all_configurator_power_text.laser_configuration
WHERE all_configurator_lasers_power.laser_configuration = 1
此外,我建议添加一些速记引用以提高可读性。这些年来,它可以在让您保持理智方面发挥重要作用:
SELECT * FROM all_configurator_power_text text
INNER JOIN all_configurator_lasers_power lasers
ON lasers.laser_configuration = text.laser_configuration
WHERE lasers.laser_configuration = 1
关于mysql - 在 MySQL 中连接两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126137/